【问题标题】:How to count the number of sentences in a text in R?如何计算R中文本中的句子数?
【发布时间】:2012-09-26 08:51:12
【问题描述】:

我使用 readChar() 函数将文本读入 R。我的目的是检验文本句子中出现字母“a”的次数与出现字母“b”的次数一样多的假设。我最近发现了{stringr} 包,它对我的​​文本做了很多有用的事情,例如计算字符数和整个文本中每个字母的出现总数。现在,我需要知道整个文本中的句子数量。 R是否有任何功能可以帮助我做到这一点?非常感谢!

【问题讨论】:

    标签: r text-mining


    【解决方案1】:

    感谢@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

    包中还支持三种语言。您只需要安装并加载相应的模型文件即可。

    1. {openNLPmodels.es} 西班牙语
    2. {openNLPmodels.ge} 德语
    3. {openNLPmodels.th} 泰语

    【讨论】:

    【解决方案2】:

    您正在寻找的是句子标记化,它并不像看起来那么简单,即使在英语中也是如此(像“我遇到了 Bennett 博士,约翰逊夫人的前夫。”这样的句子可以包含句号)。

    R 绝对不是自然语言处理的最佳选择。如果你精通Python,我建议你看看nltk 模块,它涵盖了这个和许多其他主题。您也可以从this blog post 复制代码,它会进行句子标记和单词标记。

    如果你想坚持使用 R,我建议你计算句尾字符(.?!),因为你可以计算字符。使用正则表达式的一种方法是这样的:

    text <- 'Hello world!! Here are two sentences for you...'
    length(gregexpr('[[:alnum:] ][.!?]', text)[[1]])
    

    【讨论】:

    • 为什么 R 不是一个好的选择,@SavedByJESUS 似乎找到了一个包含将文本拆分为句子的功能的包。此外,由于您给自己的原因,您在 R 中的解决方案并不是真正的解决方案,例如法斯托夫博士。
    • @PaulHiemstra R 是一种快速发展的编程语言,每天都会添加所有额外的包,以至于很难跟上一切:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 2013-10-11
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多