【问题标题】:Tokenizing sentences with unnest_tokens(), ignoring abbreviations使用 unnest_tokens() 标记句子,忽略缩写
【发布时间】:2017-11-09 21:15:09
【问题描述】:

我正在使用出色的 tidytext 包来标记多个段落中的句子。例如,我想采取以下段落:

“我完全相信达西先生没有缺陷。他自己拥有它,毫不掩饰。”

并将其标记为两个句子

  1. “我完全相信达西先生没有缺陷。”
  2. “他自己拥有它,毫不掩饰。”

但是,当我使用 tidytext 的默认句子标记器时,我得到三个句子。

代码

df <- data_frame(Example_Text = c("I am perfectly convinced by it that Mr. Darcy has no defect. He owns it himself without disguise."))


unnest_tokens(df, input = "Example_Text", output = "Sentence", token = "sentences")

结果

# A tibble: 3 x 1
                              Sentence
                                <chr>
1 i am perfectly convinced by it that mr.
2                    darcy has no defect.
3    he owns it himself without disguise.

什么是使用tidytext 标记句子但又不会遇到“先生”等常见缩写问题的简单方法?或“博士”被解释为句尾?

【问题讨论】:

  • 下面有很好的答案。为了清楚起见,tidytext 中的默认分词来自于分词器包,您可以在这里看到句子分词是如何实现的:github.com/ropensci/tokenizers

标签: r text tidytext


【解决方案1】:

您可以使用正则表达式作为拆分条件,但不能保证这将包括所有常见的恐怖:

unnest_tokens(df, input = "Example_Text", output = "Sentence", token = "regex",
              pattern = "(?<!\\b\\p{L}r)\\.")

结果:

# A tibble: 2 x 1
                                                     Sentence
                                                        <chr>
1 i am perfectly convinced by it that mr. darcy has no defect
2                         he owns it himself without disguise

您当然可以随时创建自己的常用标题列表,并根据该列表创建正则表达式:

titles =  c("Mr", "Dr", "Mrs", "Ms", "Sr", "Jr")
regex = paste0("(?<!\\b(", paste(titles, collapse = "|"), "))\\.")
# > regex
# [1] "(?<!\\b(Mr|Dr|Mrs|Ms|Sr|Jr))\\."

unnest_tokens(df, input = "Example_Text", output = "Sentence", token = "regex",
              pattern = regex)

【讨论】:

  • 不幸的是,此解决方案会中断以“引号”结尾的句子。 (在美国排版中,我们将结束标点符号放在引号内。)如果您要去掉标点符号,这可能会或可能不会重要。
【解决方案2】:

corpusquanteda 在确定句子边界时对缩写词都有特殊处理。以下是使用 corpus 拆分句子的方法:

library(dplyr)
library(corpus)
df <- data_frame(Example_Text = c("I am perfectly convinced by it that Mr. Darcy has no defect. He owns it himself without disguise."))

text_split(df$Example_Text, "sentences")
##   parent index text                                                         
## 1 1          1 I am perfectly convinced by it that Mr. Darcy has no defect. 
## 2 1          2 He owns it himself without disguise.

如果您想坚持使用unnest_tokens,但想要更详尽的英文缩写列表,您可以遵循@user 的建议,但使用corpus 缩写列表(其中大部分取自通用语言环境数据存储库):

abbrevations_en
##  [1] "A."       "A.D."     "a.m."     "A.M."     "A.S."     "AA."       
##  [7] "AB."      "Abs."     "AD."      "Adj."     "Adv."     "Alt."    
## [13] "Approx."  "Apr."     "Aug."     "B."       "B.V."     "C."      
## [19] "C.F."     "C.O.D."   "Capt."    "Card."    "cf."      "Col."    
## [25] "Comm."    "Conn."    "Cont."    "D."       "D.A."     "D.C."    
## (etc., 155 total)

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 2021-12-25
    • 2021-07-03
    相关资源
    最近更新 更多