2016-04-12 4 views
0

私はPythonを学んでおり、複数のファイルでキーワードを再帰的に検索したいと考えています。Pythonは複数のファイルに文字列を再帰的に見つけ、ファイルパスを返します

ディレクトリ内に*.docという拡張子があるはずの関数例があります。 次に、このファイル拡張子を持つ各ファイルを開き、読み取る必要があります。 ファイルを読み取っているときにキーワードが見つかった場合、関数はファイルパスを識別し、それを出力する必要があります。

キーワードが見つからない場合、pythonは続行する必要があります。あなたが私にこのコードを修正するために手を与えることができる

def find_word(extension, word): 
     # define the path for os.walk 
     for dname, dirs, files in os.walk('/rootFolder'): 
      #search for file name in files: 
      for fname in files: 
        #define the path of each file 
        fpath = os.path.join(dname, fname) 
        #open each file and read it 
        with open(fpath) as f: 
         data=f.read() 
        # if data contains the word 
        if word in data: 
         #print the file path of that file 
         print (fpath) 
        else: 
         continue 

:?、私は2つの引数を取る関数を定義していることを行うには

おかげで、

+0

あなたは私たちにいくつかの入力を与えることができる、といくつかの出力が、あなたは何を期待し、コードが失敗したどこ? – Whitefret

答えて

1

.docファイルは、彼らは、単純なテキストエディタやpythonのopenメソッドを持つオープン習慣すなわち、リッチテキストファイルです。この場合、python-docxのような他のpythonモジュールを使うことができます。

更新

(Word 2007のに以前)のdocファイルの場合、あなたはまた、そのようなcatdocやantiwordなどの他のツールを使用することができます。以下を試してください。

import subprocess 


def doc_to_text(filename): 
    return subprocess.Popen(
     'catdoc -w "%s"' % filename, 
     shell=True, 
     stdout=subprocess.PIPE 
    ).stdout.read() 

print doc_to_text('fixtures/doc.doc') 
+0

ご返信ありがとうございます。 Python-docxは.docxファイルでうまく動作しますが、.docファイルでは動作しません。なにか提案を?ありがとう! –

+0

私は答えを更新しました。それが役に立てば幸い。 – Xiflado

1
def find_word(extension, word): 
    for root, dirs, files in os.walk('/DOC'): 
     # filter files for given extension: 
     files = [fi for fi in files if fi.endswith(".{ext}".format(ext=extension))] 
     for filename in files: 
      path = os.path.join(root, filename) 
      # open each file and read it 
      with open(path) as f: 
       # split() will create list of words and set will 
       # create list of unique words 
       words = set(f.read().split()) 
       if word in words: 
        print(path) 
関連する問題