I have 2 Files, Names.txt and Paragraph.txt
Names.txt
John Anna Ron David
Paragraph.txt
David, who has been embodying Larry David for years on Curb Your Enthusiasm, which could technically come back for another season. Then, one by one, John Barrasso, John McCain, John Thune, Orrin Hatch, and Jeff Flake changed their votes to yes.
The goal is to loop through the Paragraph.txt file, with Names.txt values, and create a variable for each name, that is found in Names.txt
4 Variables have to be created, Integers, and the value of each variable, has to be the number of times the name popped up in Paragraph.txt.
Example; there has to be a variable called David which is equal to 2, since the name David appeared 2 times in Paragraph.txt
How can I achieve this, using for loops?
Any suggestions is welcomed!
CodePudding user response:
this is relatively easy to do with Python's re (Regular Expressions) library.
import re
output = {}
with open('Names.txt', 'r') as names_file:
with open('Paragraph.txt', 'r') as paragraph_file:
names = names_file.read().split(' ')
paragraph = paragraph_file.read()
for name in names:
output[name] = len(re.findall(name, paragraph))
print(output)