[英]Reading a file into a list on python. How to take out words
I am reading a file into a list and spliting it so that every word is in a list. 我正在将文件读入列表并将其拆分,以便每个单词都在列表中。 However I do not want specific words to be brought up in the list, I would like to skip them. 但是,我不想在列表中出现特定的单词,我想跳过它们。 I called the trash list filterList written below. 我称下面的垃圾列表filterList。
this is my code: 这是我的代码:
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
I am getting this error: 我收到此错误:
AttributeError: 'str' object has no attribute 'append'
Can someone help ? 有人可以帮忙吗? thanks 谢谢
You need to give, 你需要付出
aList.append(word)
List object only has the attribute append
. 列表对象仅具有属性append
。 And also you need to declare the list first. 而且您还需要先声明列表。 Then only you could append the items to that list. 然后,只有您可以将项目追加到该列表中。
ie, 即
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.