【问题标题】:Replacing a character with \n in a regex then turning the text into a quanteda corpus在正则表达式中用 \n 替换字符,然后将文本转换为 quanteda 语料库
【发布时间】:2019-05-07 16:40:38
【问题描述】:

我有一些经过 OCR 处理的文本。 OCR 放置了很多换行符 (\n),它们不应该是。但也错过了很多应该在那里的新线路。

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

我可以创建一个基本的语料库。但问题是我不能把它分成几段。如果我使用
corpus_reshape(corps, 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

【问题讨论】:

    标签: r regex gsub quanteda


    【解决方案1】:

    我建议在将文本放入语料库之前使用正则表达式替换来清理文本。文本中的技巧是找出要删除换行符的位置以及要保留它们的位置。我从您的问题中猜测您想要删除“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)我们通过将 50 替换为新的 "\n" 添加了一个换行符。

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

    【讨论】:

    • 它似乎不起作用。我仍然无法使用 corpus_reshape() 来获取段落。 stri_replace_all_regex() 创建的新段落似乎没有创建分区。
    • corpus_reshape(x, to = "paragraphs") 查找两个换行符作为段落分隔符。您需要在段落标记之前在文本中添加第二个换行符,例如在“Hello”之前。但是,这不是您问题的明确部分。
    • 做到了,谢谢。你说得对,我的问题不清楚。我正在学习 - 对此感到抱歉。
    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多