2017-07-28 17 views
0

テキストファイルの各行を読み取り、キーワードを検索するPython関数を記述しようとしています。行を新しいテキストドキュメントにエクスポートしようとしています。これは本質的にテキストの行をフィルタリングする方法を作り出すでしょう。ここで私はこれまで持っているものです。キーワードPythonの.txtファイルで出力文書を検索してエクスポートする

#trying to filter and print a line that contains a keyword in a csv or txt 

file 
import subprocess 
import csv 

def findandsearch(word): 
    textfile=open('textHCPC17_CONTR_ANWEB.txt', 'r+') 
    #openign the selected text file 
    outputfile=input('CMSOUTPUT.txt') 
    #classifying an ouput file 
    word=s'education' #designating a keyword 
    for line in textfile: 
     textfile.readline() 
     if word in textfile: #creating if clause 
      print('this is a match') #printing that this is match 
      outputfile.write(word) #I want to write the selected line of the text in the output file 
      textfile.close() #closing the original file 
      print(word) #I want to print the results 
      return #ending function 

私は構文エラーに実行しているわけではないとして任意の助けいただければ幸いですが、私の出力ファイルは空白です。あなたは、文字列とファイルオブジェクトとの間の比較を持っており、それも奇妙に聞こえる句あれば、あなたは

for line in textfile: 
    if word in line: 
     print('blahblah') 
     outputfile.write(line) 
     textfile.close() 
     print(line) 
     return 

答えて

0

あなたのforループは次のようになります。Pythonドキュメントで-S
この解決策であっても説明されていますより良い:python doc - input and output

+0

ああ、これは意味があります。助けてくれてありがとう! –

関連する問題