【问题标题】:Split text by sentence but not by special patterns按句子而不是特殊模式拆分文本
【发布时间】:2018-05-29 10:42:59
【问题描述】:

这是我的示例文本:

text = "First sentence. This is a second sentence. I like pets e.g. cats or birds."

我有一个按句子分割文本的功能

library(stringi)
split_by_sentence <- function (text) {

  # split based on periods, exclams or question marks
  result <- unlist(strsplit(text, "\\.\\s|\\?|!") )

  result <- stri_trim_both(result)
  result <- result [nchar (result) > 0]

  if (length (result) == 0)
    result <- ""

  return (result)
}

实际上是由标点符号分割的。这是输出:

> split_by_sentence(text)
[1] "First sentence"            "This is a second sentence" "I like pets e.g"           "cats or birds." 

是否有可能排除“例如”之类的特殊模式?

【问题讨论】:

  • 谢谢,但您的解决方案删除了​​“例如”。我想保留这个。

标签: r regex split


【解决方案1】:
library(tokenizers)

text = "First sentence. This is a second sentence. I like pets e.g. cats or birds."
tokenize_sentences(text)

输出是:

[[1]]
[1] "First sentence."                 "This is a second sentence."      "I like pets e.g. cats or birds."

【讨论】:

  • 效果很好。但实际上我有德语文本,这个函数例如在“z.B.”处分裂。 (德语相当于“例如”)如果可以解决这个问题,我会非常高兴。
  • 在这种情况下,@Cath 建议的正则表达式解决方案是更好的选择,因为在此示例中,openNLP 中的 Maxent_Sent_Token_Annotator 等内置函数也失败了。
【解决方案2】:

在您的模式中,如果前面至少有 2 个字母数字字符(使用环视),您可以指定要在后跟空格的任何标点符号处拆分。这将导致:

unlist(strsplit(text, "(?<=[[:alnum:]]{3})[?!.]\\s", perl=TRUE))
#[1] "First sentence"                  "This is a second sentence"       "I like pets e.g. cats or birds."

如果你想保留标点符号,那么你可以在look-behind里面添加模式并且只在空格上分割:

unlist(strsplit(text, "(?<=[[:alnum:]]{3}[[?!.]])\\s", perl=TRUE))
# [1] "First sentence."                 "This is a second sentence."      "I like pets e.g. cats or birds."

text2 <- "I like pets (cats and birds) and horses. I have 1.8 bn. horses."

unlist(strsplit(text2, "(?<=[[:alnum:]]{3}[?!.])\\s", perl=TRUE))
#[1] "I like pets (cats and birds) and horses." "I have 1.8 bn. horses."

注意:如果标点符号后面可能有多个空格,则可以在模式中使用\\s+ 而不是\\s

【讨论】:

  • @WinterMensch 看到编辑,它现在应该适用于您的数据(除非您有 3 个或更多字母的快捷方式,但它可能是这样的......)。让我知道是否可以。 (我也改变了标记,所以它只有点、感叹号和问号)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2013-04-28
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多