从列表中删除标点符号

2024-07-07 08:04:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个:

words = ["Alice's", 'Adventures', 'in', 'Wonderland', "ALICE'S", 'ADVENTURES', 'IN', 'WONDERLAND', 'Lewis', 'Carroll', 'THE', 'MILLENNIUM', 'FULCRUM', 'EDITION', '3.0', 'CHAPTER', 'I', 'Down', 'the', 'Rabbit-Hole', 'Alice', 'was']

remove_strings = str.maketrans('                           ', '!*01.23456,789-\,?\'\.(:;)\"!')

words = [s.translate(remove_strings) for s in words]
words = [words.lower() for words in words]

我想去掉所有的标点符号和数字

但它只是转换成小写,并没有像我想的那样去掉标点符号

我做错了什么


Tags: inforremovewordsalice标点符号stringslewis
1条回答
网友
1楼 · 发布于 2024-07-07 08:04:27

str.maketrans将第一个参数中指定的字符映射到第二个参数,因此您实际上只是使用当前代码将一个空格映射到另一个字符。因此,一个快速解决方案是简单地交换两个参数:

remove_strings = str.maketrans('!*01.23456,789-\,?\'\.(:;)\"!', '                           ')

更简单的方法是使用正则表达式替换,用空格替换所有非字母:

import re

words = [re.sub('[^a-z]', ' ', word, flags=re.I).lower() for word in words]

相关问题 更多 >