【发布时间】:2012-09-26 08:51:12
【问题描述】:
我使用 readChar() 函数将文本读入 R。我的目的是检验文本句子中出现字母“a”的次数与出现字母“b”的次数一样多的假设。我最近发现了{stringr} 包,它对我的文本做了很多有用的事情,例如计算字符数和整个文本中每个字母的出现总数。现在,我需要知道整个文本中的句子数量。 R是否有任何功能可以帮助我做到这一点?非常感谢!
【问题讨论】:
标签: r text-mining
我使用 readChar() 函数将文本读入 R。我的目的是检验文本句子中出现字母“a”的次数与出现字母“b”的次数一样多的假设。我最近发现了{stringr} 包,它对我的文本做了很多有用的事情,例如计算字符数和整个文本中每个字母的出现总数。现在,我需要知道整个文本中的句子数量。 R是否有任何功能可以帮助我做到这一点?非常感谢!
【问题讨论】:
标签: r text-mining
感谢@gui11aume 的回答。我刚刚发现可以帮助完成这项工作的一个非常好的包是{openNLP}。这是执行此操作的代码:
install.packages("openNLP") ## Installs the required natural language processing (NLP) package
install.packages("openNLPmodels.en") ## Installs the model files for the English language
library(openNLP) ## Loads the package for use in the task
library(openNLPmodels.en) ## Loads the model files for the English language
text = "Dr. Brown and Mrs. Theresa will be away from a very long time!!! I can't wait to see them again." ## This sentence has unusual punctuation as suggested by @gui11aume
x = sentDetect(text, language = "en") ## sentDetect() is the function to use. It detects and seperates sentences in a text. The first argument is the string vector (or text) and the second argument is the language.
x ## Displays the different sentences in the string vector (or text).
[1] "Dr. Brown and Mrs. Theresa will be away from a very long time!!! "
[2] "I can't wait to see them again."
length(x) ## Displays the number of sentences in the string vector (or text).
[1] 2
{openNLP} 包非常适合在 R 中进行自然语言处理,您可以在here 找到一个很好的简短介绍,或者您可以查看包的文档here。
包中还支持三种语言。您只需要安装并加载相应的模型文件即可。
{openNLPmodels.es} 西班牙语 {openNLPmodels.ge} 德语 {openNLPmodels.th} 泰语【讨论】:
openNLP 包在几年前发生了翻天覆地的变化。检查此问题的第二个答案:stackoverflow.com/questions/18370518/…
您正在寻找的是句子标记化,它并不像看起来那么简单,即使在英语中也是如此(像“我遇到了 Bennett 博士,约翰逊夫人的前夫。”这样的句子可以包含句号)。
R 绝对不是自然语言处理的最佳选择。如果你精通Python,我建议你看看nltk 模块,它涵盖了这个和许多其他主题。您也可以从this blog post 复制代码,它会进行句子标记和单词标记。
如果你想坚持使用 R,我建议你计算句尾字符(.、?、!),因为你可以计算字符。使用正则表达式的一种方法是这样的:
text <- 'Hello world!! Here are two sentences for you...'
length(gregexpr('[[:alnum:] ][.!?]', text)[[1]])
【讨论】: