如何删除标点符号?

use*_*472 7 python nlp nltk

在Python中使用NLTK的tokenizer .

已经在论坛上删除了标点符号的大量答案.但是,它们都没有一起解决所有以下问题:

  1. 连续多个符号.例如,句子:他说,"就是这样." 因为有一个逗号后跟引号,所以标记器不会删除."在标题中.标记器将给出''他','说',','','',','s','它. '而不是['他','说','那','s','它'].其他一些例子包括'...',' - ','!?',',''等等.
  2. 删除句子末尾的符号.即句子:Hello World.标记器将给出['Hello','World.']而不是['Hello','World'].请注意"世界"一词末尾的句号.其他一些例子包括任何字符的开头,中间或末尾的' - ',','.
  3. 删除前面和后面带符号的字符.即'*u*', '''','""'

有一种解决这两个问题的优雅方式吗?

alv*_*vas 12

解决方案1:标记并删除标记的标点符号

>>> from nltk import word_tokenize
>>> import string
>>> punctuations = list(string.punctuation)
>>> punctuations
['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
>>> punctuations.append("''")
>>> sent = '''He said,"that's it."'''
>>> word_tokenize(sent)
['He', 'said', ',', "''", 'that', "'s", 'it', '.', "''"]
>>> [i for i in word_tokenize(sent) if i not in punctuations]
['He', 'said', 'that', "'s", 'it']
>>> [i.strip("".join(punctuations)) for i in word_tokenize(sent) if i not in punctuations]
['He', 'said', 'that', 's', 'it']
Run Code Online (Sandbox Code Playgroud)

解决方案2:删除标点符号然后标记化

>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> sent = '''He said,"that's it."'''
>>> " ".join("".join([" " if ch in string.punctuation else ch for ch in sent]).split())
'He said that s it'
>>> " ".join("".join([" " if ch in string.punctuation else ch for ch in sent]).split()).split()
['He', 'said', 'that', 's', 'it']
Run Code Online (Sandbox Code Playgroud)


πόδ*_*κύς 6

如果你想一次性对你的字符串进行标记,我认为你唯一的选择就是使用它nltk.tokenize.RegexpTokenizer.以下方法允许您在删除标点符号之前使用标点符号作为标记来删除字母表中的字符(如第三个要求中所述).换句话说,这种方法将*u*在剥离所有标点符号之前删除.

那么,解决这个问题的一种方法就是将间隙标记为:

>>> from nltk.tokenize import RegexpTokenizer
>>> s = '''He said,"that's it." *u* Hello, World.'''
>>> toker = RegexpTokenizer(r'((?<=[^\w\s])\w(?=[^\w\s])|(\W))+', gaps=True)
>>> toker.tokenize(s)
['He', 'said', 'that', 's', 'it', 'Hello', 'World']  # omits *u* per your third requirement
Run Code Online (Sandbox Code Playgroud)

这应符合您在上面指定的所有三个标准.但请注意,此标记生成器不会返回令牌等"A".此外,我只对以标点符号开头结尾的单个字母进行标记.否则,"去吧." 不会返回令牌.您可能需要以其他方式细化正则表达式,具体取决于您的数据是什么以及您的期望是什么.