如何使用for循环从列表中删除标点符号?我已经导入了一个标点符号字符串,我使用它来比较原始列表,以便删除标点符号。
这是我目前的代码:
import string
l = list(string.punctuation)
print(punctuation_list)
w = ["haythem", "is", "eating", "tacos.", "haythem", "loves", "tacos", "", ":"]
w_clean = list()
for x in w:
for y in l:
if y in x:
x = x.replace(y,'')
w_clean.append(x)
break
print(w_clean)产出如下:
['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
['tacos', '']所需产出是:
['haythem', 'is', 'eating', 'tacos', 'haythem', 'loves', 'tacos']发布于 2021-07-14 15:00:42
以下是Ant的答案
import string
l = list(string.punctuation)
w = ["haythem", "is", "eating", "tacos.", "haythem", "loves", "tacos", "", ":"]
w_clean = []
for x in w:
for y in l:
if y in x:
x = x.replace(y,'')
if x:
w_clean.append(x)
print(w_clean)按要求输出
发布于 2021-07-14 11:20:10
当前,只有在找到标点符号时才会追加字符串。
您可以删除if子句,也可以添加一个也附加其他字符串的else。
另外,你应该删除断点块,除非你只想删除第一个标点符号。
因此,内部块应该如下所示:
if y in x:
x = x.replace(y,'')
w_clean.append(x)
else:
w_clean.append(x)还可以查看this answer以获得更有效的替换方法。
发布于 2021-07-14 11:25:46
在内部循环中的代码中,您正在检查标点符号是否在单词中。如果是,将标点符号替换为空字符串并添加到输出列表中。因此,您的代码正在相应地工作,您所写的。
但我想要的是返回没有标点符号的输入单词列表。我还假设您不需要列表中的空单词,并且允许重复(比如tacos),因此您可以这样修改代码:
for x in w:
for y in punctuation_list:
if y in x:
x = x.replace(y,'')
if(len(x)>0):
w_clean.append(x) 如果要保留空字符串,只需删除if条件并在第一个循环下添加w_clean.append(x)即可。
https://stackoverflow.com/questions/68376945
复制相似问题