2016-04-14 18 views
0

私がコードのフレーズを入力したときに、スクリプトを見ているディレクトリに入力したときにコードを修正しようとしています言葉はそれはまだ句を示したことはディレクトリ内にあり、それがどこにあるかを返しますまたはまたはCATまたはを綴られている語句を検索します。以下のコードを添付しました。ユーザが入力した句をPythonで入力する方法

import os 

phrase_to_look_for = input("What phrase would you like to look for?") 
name_of_directory = input("What is the name of your directory?") 
for subdir, dirs, files in os.walk(name_of_directory, phrase_to_look_for): 
     for file in files: 
       file_path = os.path.join(name_of_directory, subdir, file) 
       file_to_search = open(file_path,'r') 
       try: 
         contents_of_file = file_to_search.read() 
       except: 
         contents_of_file = '' 
       if phrase_to_look_for in contents_of_file: 
         print("The word is in the file: " + file) 
       else: 
         print("The phrase is not in the file.") 

ありがとうございました。

答えて

1

単にlowerファイルの内容やユーザーの入力:

phrase_to_look_for = input("What phrase would you like to look for?").lower() 

contents_of_file = file_to_search.read().lower() 

これは効果的に検索する場合は、小文字を区別しない作り、小文字のすべてを行います。私はあなたの空のexceptは、あなたが実際に扱いたいもの、つまりexcept IOError:

+0

であるべきであると指摘しなければなりません。それでもまだスローしますが、フレーズはファイルにありません。 – Jared

+0

@ Jaredはそれを投げますか?これはあなたの実際のコードではありませんか? –

+0

私の用語を訂正しないでください。私はPythonスクリプトに問題があり、あなたの言うことがうまくいかないと助けを求めています。 – Jared