How To Search A Text File For A Specific Word In Python
I want to find words in a text file that match words stored in an existing list called items, the list is created in a previous function and I want to be able to use the list in th
Solution 1:
You can use regexp the following way:
>>> import re
>>> words=['car','red','woman','day','boston']
>>> word_exp='|'.join(words)
>>> re.findall(word_exp,'the red car driven by the woman',re.M)
['red', 'car', 'woman']
The second command creates a list of acceptable words separated by "|". To run this on a file, just replace the string in 'the red car driven by the woman' for open(your_file,'r').read()
.
Solution 2:
This may be a bit cleaner. I feel class is an overkill here.
defcreatelist():
items = []
withopen('words.txt') asinput:
for line ininput:
items.extend(line.strip().split(','))
return items
print(createlist())
# store the list
word_list = createlist()
withopen('file.txt') as f:
# split the file content to words (first to lines, then each line to it's words)for word in (sum([x.split() for x in f.read().split('\n')], [])):
# check if each word is in the listif word in word_list:
# do something with wordprint word + " is in the list"else:
# word not in listprint word + " is NOT in the list"
Solution 3:
There is nothing like Regular expressions in matching https://docs.python.org/3/howto/regex.html
items=['one','two','three','four','five'] #your items list created previouslyimport re
file=open('text.txt','r') #load your file
content=file.read() #save the read output so the reading always starts from beginingfor i in items:
lis=re.findall(i,content)
iflen(lis)==0:
print('Not found')
eliflen(lis)==1:
print('Found Once')
eliflen(lis)==2:
print('Found Twice')
else:
print('Found',len(lis),'times')
Post a Comment for "How To Search A Text File For A Specific Word In Python"