私信  •  关注

Matt L.

Matt L. 最近创建的主题
Matt L. 最近回复了

错误出现在以下代码行中:

for word in all_words:
    word = word.lower()
    word = word.translate(str.maketrans('','',string.punctuation))

索引变量 word 在这种情况下,将由循环临时创建。不能就地更换。见 https://eli.thegreenplace.net/2015/the-scope-of-index-variables-in-pythons-for-loops/

相反,有两种方法可以循环和替换>方法1是追加到新列表中,如下所示:

all_words_new = []
for word in all_words:
    new_word = word.lower()
    newer_word = new_word.translate(str.maketrans('','',string.punctuation))
    all_words_new.append(newer_word)

选项2是一个列表理解,它有点高级。

all_words_new = [word.lower() for word in all_words]
all_words_newer = [word.translate(str.maketrans('','',string.punctuation)) for word in all_words]

有关更多列表理解,请参见 https://www.pythonforbeginners.com/basics/list-comprehensions-in-python