我正在使用来自 NLTK in Python 的分词器。
论坛上已经有一大堆删除标点符号的答案。但是,它们都没有同时解决以下所有问题:
- 一行中有多个符号。例如,句子:他说,“就是这样。”因为有一个逗号后跟引号,分词器不会删除句子中的“。”。分词器将给出 ['He', 'said', ',', 'that', 's', 'it. '] 而不是 ['他','说','那个','s','它']。其他一些示例包括“...”、“--”、“!?”、“、”等。
- 删除句末的符号。即句子:Hello World。分词器将给出 ['Hello', 'World.'] 而不是 ['Hello', 'World']。注意“世界”一词末尾的句点。其他一些示例包括任何字符开头、中间或结尾的“--”、“、”。
- 删除前后带有符号的字符。即
'*u*', '''','""'
是否有解决这两个问题的优雅方法?
最佳答案
解决方案 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']
解决方案 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']
关于python - 如何去除标点符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23317458/