首页 > 解决方案 > 在python中删除标点符号

问题描述

我正在尝试从 python 中的给定字符串中删除标点符号。

它运行良好,但是我使用的数据包含大量“:D”或“:)”或“:(”。

因此,当我分析数据时,我最终会删除所有这些文本微笑或仅删除“:”来表示“:D”的情况。

以下是示例代码:

import string
import nltk

example_string = 'I would like to remove some punctiation, \
                  however some stuff like \':D\' causes errors. \
                  How would I not get rid of \':\', \
                  if it is followed by a \'D\'? '


translator = str.maketrans('', '', string.punctuation)

line = example_string.translate(translator)
line = nltk.word_tokenize(line)
line = [word.lower() for word in line
                     if word not in ['\'', '’', '”', '“']]

print(line)

这产生作为输出:

['i', 'would', 'like', 'to', 'remove', 'some', 'punctiation',
 'however', 'some', 'stuff', 'like', 'd', 'causes', 'errors',
 'how', 'would', 'i', 'not', 'get', 'rid', 'of', 'if', 'it',
 'is', 'followed', 'by', 'a', 'd']

我想要产生的是(检查第二行第 5 个字)

['i', 'would', 'like', 'to', 'remove', 'some', 'punctiation',
 'however', 'some', 'stuff', 'like', ':d', 'causes', 'errors',
 'how', 'would', 'i', 'not', 'get', 'rid', 'of', 'if', 'it',
 'is', 'followed', 'by', 'a', 'd']

它还将删除所有“:)”或“:(”。

有没有办法不删除“:”,如果它后面跟着一个“d”?

或不删除“)”或“(”,如果前一个字符是“:”?

标签: pythonstringnltkpunctuation

解决方案


推荐阅读