python - 如何去除标点符号?

标签 python nlp nltk

我正在使用来自 NLTK in Python 的分词器。

论坛上已经有一大堆删除标点符号的答案。但是,它们都没有同时解决以下所有问题:

  1. 一行中有多个符号。例如,句子:他说,“就是这样。”因为有一个逗号后跟引号,分词器不会删除句子中的“。”。分词器将给出 ['He', 'said', ',', 'that', 's', 'it. '] 而不是 ['他','说','那个','s','它']。其他一些示例包括“...”、“--”、“!?”、“、”等。
  2. 删除句末的符号。即句子:Hello World。分词器将给出 ['Hello', 'World.'] 而不是 ['Hello', 'World']。注意“世界”一词末尾的句点。其他一些示例包括任何字符开头、中间或结尾的“--”、“、”。
  3. 删除前后带有符号的字符。即 '*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/

相关文章:

python - 尝试扩展行数据并转换为 DataFrame,出现此错误 : AttributeError: 'float' object has no attribute 'keys'

python - 查找错误 : Resource 'corpora/stopwords' not found

python - NLTK 词干提取不通过简单的案例

python - Pandas 中的 Parse_dates

python - reshape numpy 数组

Python - 在 map 中应用成员函数

vector - 即使不是单词,spacy如何生成单词向量?

python - Nltk和Python,绘制ROC曲线

python - Tensorflow 2.0 拥抱人脸变压器、TFBertForSequenceClassification、推理中意外的输出维度

python - 对单词和字符进行分组和分类