【问题标题】:How to strip string from punctuation except apostrophes for NLP如何从标点符号中去除字符串,除了 NLP 的撇号
【发布时间】:2020-01-23 11:42:04
【问题描述】:

我正在使用以下“最快”的方式从字符串中删除标点符号:

text = file_open.translate(str.maketrans("", "", string.punctuation))

但是,它会从标记中删除所有标点符号,包括撇号,例如 shouldn't 将其转换为 shouldnt

问题是我将 NLTK 库用于停用词,而标准停用词不包括没有撇号的此类示例,而是具有 NLTK 将生成的标记,如果我使用 NLTK 标记器来拆分我的文本。例如shouldnt 包含的停用词是shouldn, shouldn't, t

我可以添加额外的停用词或从 NLTK 停用词中删除撇号。但是这两种解决方案在某种程度上似乎都不“正确”,因为我认为在进行标点符号清理时应该留下撇号。

在进行快速标点清理时,有什么方法可以留下撇号吗?

【问题讨论】:

  • 为什么不从string.punctuation 中排除撇号?
  • 我不知道这是可能的,像这样的? string.punctuation.replace(" ' ", "")

标签: python nlp nltk


【解决方案1】:
>>> from string import punctuation
>>> type(punctuation)
<class 'str'>
>>> my_punctuation = punctuation.replace("'", "")
>>> my_punctuation
'!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~'
>>> "It's right, isn't it?".translate(str.maketrans("", "", my_punctuation))
"It's right isn't it"

【讨论】:

    【解决方案2】:

    编辑自this answer

    import re
    
    s = "This is a test string, with punctuation. This shouldn't fail...!"
    
    text = re.sub(r'[^\w\d\s\']+', '', s)
    print(text)
    

    这会返回:

    这是一个带有标点符号的测试字符串 这应该不会失败

    正则表达式解释:

    [^] 匹配除块引号内的所有内容
    \w 匹配任何单词字符(等于[a-zA-Z0-9_]
    \d 匹配一个数字(等于[0-9]
    @ 987654329@ 匹配任何空白字符(等于 [\r\n\t\f\v ]
    \' 匹配字符 ' 字面意思(区分大小写)
    + 匹配一次到无限次,尽可能多次,给出根据需要返回

    你可以试试here

    【讨论】:

    • 感谢详细的正则表达式解释!我注意到正则表达式在解决 NLP 问题方面非常流行。我需要在某个时候做一些学习。
    【解决方案3】:

    如何使用

    text = file_open.translate(str.maketrans(",.", "  "))
    

    并将您想要忽略的其他字符添加到第一个字符串中。

    【讨论】:

      猜你喜欢
      • 2015-07-07
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      • 2010-09-20
      • 1970-01-01
      • 2018-05-13
      相关资源
      最近更新 更多