我需要编写一个程序,该程序接收一个文本文件并询问用户一个单词,然后打印出该单词出现的每一行。 这是我到目前为止的代码,但它给了我一个错误:
text_file = open('gettysburg.txt', 'r').read()
key_word = input("What is the word?: ")
for line in text_file.readlines():
if key_word in line:
print(line)
我做错了什么?
答案 0 :(得分:1)
试试这个:
text_file = open('gettysburg.txt', 'r') # you dont need .read here
key_word = input("What is the word?: ")
for line in text_file.readlines():
if key_word in line:
print(line)
read
将整个文件内容作为单个字符串
答案 1 :(得分:1)
另一种方法是使用with
打开文件(更值得推荐):
key_word = input("What is the word?: ")
with open('gettysburg.txt', 'r') as text_file:
for line in text_file.readlines():
if key_word in line:
print(line)
请注意它的python3。