【发布时间】:2020-04-27 16:30:33
【问题描述】:
在这个论坛上讨论过类似的问题(例如here 和here),但我没有找到解决我问题的问题,所以对于一个看似相似的问题,我深表歉意。
我有一组采用 UTF-8 编码的 .txt 文件(见屏幕截图)。我正在尝试使用 tm 包在 R 中运行主题模型。然而,尽管在创建语料库时使用了 encoding = "UTF-8",但我在编码方面遇到了明显的问题。例如,我得到 scal 而不是 fiscal,inuenc 而不是 influence,并非所有标点符号都被删除,并且某些字母无法识别(例如,引号在某些情况下仍然存在,例如 view” 或 plan' 或 ændring 或孤立的引号,如“and ”或 zit 或 years - 因此带有应该已删除的破折号)。这些术语也显示在术语的主题分布中。我之前在编码方面遇到了一些问题,但是使用"encoding = "UTF-8" 创建了用于解决问题的语料库。这次好像没用了。
我使用的是 Windows 10 x64,R 版本 3.6.0 (2019-04-26),tm 包的 0.7-7 版本(都是最新的)。我将非常感谢任何有关如何解决该问题的建议。
library(tm)
library(beepr)
library(ggplot2)
library(topicmodels)
library(wordcloud)
library(reshape2)
library(dplyr)
library(tidytext)
library(scales)
library(ggthemes)
library(ggrepel)
library(tidyr)
inputdir<-"c:/txtfiles/"
docs<- VCorpus(DirSource(directory = inputdir, encoding ="UTF-8"))
#Preprocessing
docs <-tm_map(docs,content_transformer(tolower))
removeURL <- function(x) gsub("http[^[:space:]]*", "", x)
docs <- tm_map(docs, content_transformer(removeURL))
toSpace <- content_transformer(function(x, pattern) (gsub(pattern, " ", x)))
docs <- tm_map(docs, toSpace, "/")
docs <- tm_map(docs, toSpace, "-")
docs <- tm_map(docs, toSpace, "\\.")
docs <- tm_map(docs, toSpace, "\\-")
docs <- tm_map(docs, removePunctuation)
docs <- tm_map(docs, removeNumbers)
docs <- tm_map(docs, removeWords, stopwords("english"))
docs <- tm_map(docs, stripWhitespace)
docs <- tm_map(docs,stemDocument)
dtm <- DocumentTermMatrix(docs)
freq <- colSums(as.matrix(dtm))
ord <- order(freq, decreasing=TRUE)
write.csv(freq[ord],file=paste("word_freq.csv"))
#Topic model
ldaOut <-LDA(dtm,k, method="Gibbs",
control=list(nstart=nstart, seed = seed, best=best,
burnin = burnin, iter = iter, thin=thin))
编辑:我应该在 cse 中添加,事实证明 txt 文件是使用以下 R 代码从 PDF 创建的:
inputdir <-"c:/pdf/"
myfiles <- list.files(path = inputdir, pattern = "pdf", full.names = TRUE)
lapply(myfiles, function(i) system(paste('"C:/Users/Delt/AppData/Local/Programs/MiKTeX 2.9/miktex/bin/x64/pdftotext.exe"',
paste0('"', i, '"')), wait = FALSE) )
可以下载两个示例txt文件here。
【问题讨论】:
-
请创建 2 个包含违规问题的示例 txt 文件并将它们添加到 github 或其他共享位置。现在只是猜测。如果您没有坚持使用 tm 将数据导入 R,那么 readtext 包可能有助于在 R 中正确获取数据。任何其他确保编码正确的包也可以解决问题。
-
@phiver 谢谢你的评论。我添加了两个 txt 文件,这些文件展示了我描述的大多数违规问题。除非没有办法解决这个问题,否则我更愿意使用 tm 包找到一个简单的解决方案。我非常感谢任何建议。
-
我感觉这与您使用的 pdf 阅读器有关。 scal,应该是财政,扫描可能没有正确解释,它返回“财政”,注意fi不是松散的字母,而是一个组合字母,即像æ一样的正字法连字。如果您使用包 pdftools 读取 pdf 文件会怎样?您可以在 tm 中使用 pdftools 直接阅读 pdf。或者先单独进行检查是否正常工作。
-
@phiver 比你。我试过这段代码
text <-pdf_text("c:/txt/1.pdf") write(text, "1.txt"),txt 也有同样的问题。现在即使在 txts fiscal 显示为 scal 并且当读入语料库时它变成 ufbscal
标签: r encoding utf-8 nlp topic-modeling