Mozein
Mozein

Reputation: 807

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.

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

Upvotes: 1

Views: 70

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

You need to give,

aList.append(word)

List object only has the attribute 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) 

Upvotes: 2

Related Questions