f = open("data.txt", "rt")
lines = f.read()
#word = line.split()
for line in lines:
if line == 'how' or line == 'what' or line == 'where':
print(lines, "Yes")
else:
print(lines, "No")
f.close()
I am trying to read a file and look for sentences that have how, what, where, etc. Basically sentences that are a question. And printing the sentences along with a Yes or No accordingly.
Format of Input file:
how are you
it's 7 o'clock
where is your food
Format of Output file:
how are you Yes
it's 7 o'clock No
where is your food Yes
But my code is giving no output.
The line if line == 'how' or line == 'what' or line == 'where':
suggests to me that you might want to use the logic of keyword any()
:
f = open("data.txt", "rt")
lines = f.readlines()
f.close()
with open('data_out.txt', 'w') as f:
for line in lines:
if any(question_word in line for question_word in ['how', 'what', 'where']):
output = '{} {}\n'.format(line.strip('\n'), "Yes")
print(output)
f.write(output)
else:
output = '{} {}\n'.format(line.strip('\n'), "No")
print(output)
f.write(output)
how are you Yes
it's 7 o'clock No
where is your food Yes