[英]Replacing a character with \n in a regex then turning the text into a quanteda corpus
我有一些OCR的文字。 OCR放了很多换行符(\\ n),如果它们不应该是。 但也错过了许多应该在那里的新线路。
我想删除现有的换行符并用空格替换它们。 然后用原始文本中的换行符替换特定字符。 然后将文档转换为quanteda中的语料库。
我可以创建一个基本的语料库。 但麻烦的是我不能把它分解成段落。 如果我使用
corpus_reshape(corps,to =“paragraph”,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包的简单接口,但我总是倾向于使用stringi (在其上构建stringr )。 它允许矢量化替换,因此您可以在一个函数调用中为其提供匹配的模式向量和替换。
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)我们通过用新的"\\n"
替换50来添加一个换行符。
现在,您可以使用quanteda::corpus(sample2)
构建语料库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.