如何使用for循环和string.punctuation移除列表中的标点符号
问题分析
原代码存在4个核心错误:
- 变量名错误:标点列表存储到了变量
l中,但打印时调用了未定义的punctuation_list,运行会直接抛出NameError - 追加逻辑错误:仅当检测到字符串包含标点时,才会把处理后的内容加入结果列表,本身不含标点的正常单词全部被遗漏
- 标点清理不完整:替换完一个标点就执行break,若单个字符串包含多个标点,无法完成全部清理
- 无空值过滤:原列表中的空字符串、全为标点的字符串处理后仍为空值,未做过滤
修改后可运行代码
import string punctuation_list = list(string.punctuation) # 不需要打印标点列表可注释下方代码 # print(punctuation_list) w = ["haythem", "is", "eating", "tacos.", "haythem", "loves", "tacos", "", ":"] w_clean = list() for x in w: # 遍历所有标点,对当前字符串做全量替换 for y in punctuation_list: if y in x: x = x.replace(y, '') # 仅保留非空的处理结果 if x: w_clean.append(x) print(w_clean)
输出结果
['haythem', 'is', 'eating', 'tacos', 'haythem', 'loves', 'tacos']
内容的提问来源于stack exchange,提问作者Aidan。
相关产品推荐
相关产品推荐

