我正在将文件读入列表并将其拆分,以便每个单词都在列表中。但是,我不想在列表中显示特定的单词,我想跳过它们。我称下面的垃圾列表filterList。
这是我的代码:
with open('USConstitution.txt') as f:
lines = f.read().split() #read everything into the list
filterList = ["a","an","the","as","if","and","not"] #define a filterList
for word in lines:
if word.lower() not in filterList:
word.append(aList) #place them in a new list called aList that does not contain anything in filterList
print(aList) #print that new list
我收到此错误:
AttributeError: 'str' object has no attribute 'append'
有人可以帮忙吗?谢谢
最佳答案
你需要付出
aList.append(word)
列表对象仅具有属性
append
。而且您还需要先声明列表。然后,只有您可以将项目追加到该列表中。即
with open('USConstitution.txt') as f:
lines = f.read().split() #read everything into the list
filterList = ["a","an","the","as","if","and","not"] #define a filterList
aList = []
for word in lines:
if word.lower() not in filterList:
aList.append(word) #place them in a new list called aList that does not contain anything in filterList
print(aList)