在正则表达式中用 \n 替换字符,然后将文本转换为 quanteda 语料库

Replacing a character with \n in a regex then turning the text into a quanteda corpus

我有一些文本已经过 OCR。 OCR 放了很多不应该的换行符 (\n)。但也错过了很多应该在那里的新台词。

我想删除现有的换行符并用空格替换它们。然后用原始文本中的换行符替换特定字符。然后把文档变成quanteda的语料库。

我可以创建一个基本语料库。但问题是我不能把它分成几段。如果我使用
corpus_reshape(军团, to ="paragraphs", use_docvars = TRUE) 它不会分解文档。

如果我使用corpus_segment(corps, pattern = "\n")

我收到一个错误。

rm(list=ls(all=TRUE))
library(quanteda)
library(readtext)

# Here is a sample Text
sample <- "Hello my name is Christ-
ina. 50 Sometimes we get some we-


irdness

Hello my name is Michael, 
sometimes we get some weird,


 and odd, results-- 50 I want to replace the 
 50s
"



# Removing the existing breaks
sample <- gsub("\n", " ", sample)
sample <- gsub(" {2,}", " ", sample)
# Adding new breaks
sample <- gsub("50", "\n", sample)

# I can create a corpus
corps <- corpus(sample, compress = FALSE)
summary(corps, 1)

# But I can't change to paragraphs
corp_para <- corpus_reshape(corps, to ="paragraphs", use_docvars = TRUE)
summary(corp_para, 1)

# But I can't change to paragraphs
corp_para <- corpus_reshape(corps, to ="paragraphs", use_docvars = TRUE)
summary(corp_para, 1)

corp_segmented <-  corpus_segment(corps, pattern = "\n")

# The \n characters are in both documents.... 
corp_para$documents$texts
sample

我建议在将文本放入语料库之前使用正则表达式替换来清理文本。文本中的技巧是找出要删除换行符的位置以及要保留换行符的位置。我从你的问题中猜测你想删除出现的“50”,但也可能加入由连字符和换行符分隔的单词。您可能还想在文本之间保留两个换行符?

许多用户更喜欢 stringr 包的简单界面,但我一直倾向于使用 stringistringr 被构建)代替。它允许向量化替换,因此您可以在一个函数调用中为其提供一个要匹配的模式向量和替换。

library("stringi")

sample2 <- stri_replace_all_regex(sample, c("\-\n+", "\n+", "50"), c("", "\n", "\n"),
  vectorize_all = FALSE
)
cat(sample2)
## Hello my name is Christina. 
##  Sometimes we get some weirdness
## Hello my name is Michael, 
## sometimes we get some weird,
##  and odd, results-- 
##  I want to replace the 
##  
## s

在这里,您匹配 "\n" 作为正则表达式 模式 但仅使用 "\n" 作为(文字) 替换 .

替换文本中最后一个 "s" 之前有两个换行符,因为 a) 在“50s”中的 "s" 之后已经有一个换行符 b) 我们通过用 a 替换 50 添加了一个换行符新 "\n".

现在你可以用quanteda::corpus(sample2)构建语料库了。