2017-05-15 8 views
0

テキストファイルを受け取ってユーザーに単語を尋ねるプログラムを書く必要があります。 ここにあります私がこれまでに持っているコードはエラーです:特定の単語を含むすべての行をテキストファイルに出力する方法

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) 

私は間違っていますか?

+3

しかし、それは私にエラーを与える_ - >してください!常に質問にエラーメッセージを追加する –

答えて

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は、もう一つの方法は、ファイルを開くためにwithを使用している単一の文字列

1

としてファイルの内容全体を読み込む(それはもっとお勧めします):

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であることに注意してください。

関連する問題