【问题标题】:separating last sentence from a string in R从R中的字符串中分离最后一个句子
【发布时间】:2017-04-10 20:51:31
【问题描述】:

我有一个字符串向量,我想将最后一个句子与 R 中的每个字符串分开。

句子可能以句号(.) 甚至感叹号(!) 结尾。因此,我对如何将最后一句与 R 中的字符串分开感到困惑。

【问题讨论】:

  • 类似sub(".*(\\.|\\?|\\!) ", "", yourvector)?前提是你的句子之间有空格。
  • @Scarabee 非常感谢您的回答。它的工作!如果您能指出我在 R 中学习文本挖掘的资源,那就太好了
  • 不客气。至于资源,抱歉,我不太了解文本挖掘(也不是 R),无法为您提供好的建议。

标签: r text text-mining


【解决方案1】:

您可以使用strsplit从每个字符串中获取最后一个句子,如图所示:-

## paragraph <- "Your vector here"
result <- strsplit(paragraph, "\\.|\\!|\\?")

last.sentences <- sapply(result, function(x) {
    trimws((x[length(x)]))
})

【讨论】:

  • 这个方法有个小问题:你丢失了最后一句话的标点符号。但我不知道OP是否需要它。
【解决方案2】:

如果你的输入足够干净(特别是句子之间有空格),你可以使用:

sub(".*(\\.|\\?|\\!) ", "", trimws(yourvector))

它找到以标点符号和空格结尾的最长子字符串并将其删除。

我添加了trimws,以防您的某些字符串中有尾随空格。

例子:

u <- c("This is a sentence. And another sentence!",
       "By default R regexes are greedy. So only the last sentence is kept. You see ? ",
       "Single sentences are not a problem.",
       "What if there are no spaces between sentences?It won't work.",
       "You know what? Multiple marks don't break my solution!!",
       "But if they are separated by spaces, they do ! ! !")

sub(".*(\\.|\\?|\\!) ", "", trimws(u))
# [1] "And another sentence!"                                       
# [2] "You see ?"                                                   
# [3] "Single sentences are not a problem."                         
# [4] "What if there are no spaces between sentences?It won't work."
# [5] "Multiple marks don't break my solution!!"                    
# [6] "!"  

【讨论】:

    【解决方案3】:

    此正则表达式使用 $ 锚定到字符串的末尾,允许使用可选的 '.'或者 '!'在末尾。在前面,它找到最接近的“。”或“!”作为前一句的结尾。负面回溯 ?

    s <- "Sentences may end with full stops(.) or even exclamatory marks(!). Hence i am confused as to how to separate the last sentence from a string in R."
    library (stringr)
    str_extract(s, "(?<=(\\.\\s|\\!\\s|^)).+(\\.|\\!)?$")
    

    产量

    # [1] "Hence i am confused as to how to separate the last sentence from a string in R."
    

    【讨论】:

    • 我测试了它并不能正常工作,看来你必须修复一些东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2012-03-21
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多