在文件中搜索作为问题的句子
searching for sentences that are a question in a file
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()
我正在尝试阅读一个文件并寻找包含如何、什么、在哪里等的句子。基本上是一个问题的句子。并相应地打印句子以及是或否。
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
但是我的代码没有输出。
行 if line == 'how' or line == 'what' or line == 'where':
向我建议您可能想要使用关键字逻辑 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
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()
我正在尝试阅读一个文件并寻找包含如何、什么、在哪里等的句子。基本上是一个问题的句子。并相应地打印句子以及是或否。
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
但是我的代码没有输出。
行 if line == 'how' or line == 'what' or line == 'where':
向我建议您可能想要使用关键字逻辑 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