python - 在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”?
或不删除“)”或“(”,如果前一个字符是“:”?
解决方案
推荐阅读
- javascript - 如何在 Chrome 上反转屏幕旋转的效果?
- java - 是否可以从不同类的枚举中选择随机值?
- python - 神经网络的 3d 图
- javascript - 如何使用javascript从日期输入中获取日期
- python - 从 tkinter 到 python 脚本的输入和从 python 脚本到 tkinter 的输出
- flutter - Flutter - 使用变量值渲染文本类。可能的类型问题?
- java - 如何将保存在计算机上的 jpg 添加到我编写的代码中
- ruby-on-rails - react 和 rails 中的 csrf
- asp.net-core - ASP-NET.core如何实现资源文件本地化?
- sql - SQL查询根据列分组获取总人数