Python 在所有Word和PDF文件中搜索文件夹和子文件夹中的字符串

Python 在所有Word和PDF文件中搜索文件夹和子文件夹中的字符串,python,string,pdf,ms-word,subdirectory,Python,String,Pdf,Ms Word,Subdirectory,我对Python2.7有点陌生,我想知道是否有一种方法可以在文件夹(及其所有子文件夹、PDF和Word文档)中搜索某个单词。我需要将所有包含某个关键字的PDF和Word文件编译到一个新文件夹中,因此我认为python可能是最好的方法,而不是手动浏览每个文件并搜索单词。有什么想法吗 以下是如何在文件中搜索单词的示例: files = ["example.txt", "example2.txt", "example3.txt"] matches = [False, False, False] for

我对Python2.7有点陌生,我想知道是否有一种方法可以在文件夹(及其所有子文件夹、PDF和Word文档)中搜索某个单词。我需要将所有包含某个关键字的PDF和Word文件编译到一个新文件夹中,因此我认为python可能是最好的方法,而不是手动浏览每个文件并搜索单词。有什么想法吗

以下是如何在文件中搜索单词的示例:

files = ["example.txt", "example2.txt", "example3.txt"]
matches = [False, False, False]
for f in range(3):
    fi = open(files[f], 'r')
    for line in fi:
        if "word" in line:
            matches[f] = True
            break
    fi.close()
print matches
这将打开您的文件并检查关键字“word”。至于PDF,除非你能先把它们转换成文本文件,否则这将非常困难

我强烈建议您阅读教程,例如查找目录(文件夹)等。

def pdf2text(pdf\u文件):
返回pdf文件的文本
def word2text(文档文件):
返回文档文件的文本
def搜索路径中的单词(根路径,指针):
对于os.walk(根路径)中的当前目录、目录和文件:
对于文件中的fname:
fpath=os.path.join(当前目录,fname)
如果fpath.endswith(“pdf”):
如果指针位于PDF2文本(fpath)中:
收益率路径
elif fpath.endswith(“doc”)或fpath.endswith(“docx”):
如果在word2text(fpath)中输入指针:
收益率路径
对于搜索路径中的文件名(r“C:\Users\\Documents”,“some word”):
打印(“在%r”%filename中找到“某个单词”)

我想。。。我把一些工作留给了您,作为解决问题的OP

没有真正的理由再使用Python2而不是Python3了,我建议您切换。是的,这是可能的。不过,这不是一个代码编写服务。这里的白色标记包是一些软件不使用python3的原因
def pdf2text(pdf_file):
    return text_of_pdf_file

def word2text(doc_file):
    return text_of_doc_file

def search_word_in_path(root_path,needle):
    for current_dir,dirs,files in os.walk(root_path):
        for fname in files:
           fpath = os.path.join(current_dir,fname)
           if fpath.endswith("pdf"):
              if needle in pdf2text(fpath):
                   yield fpath
           elif fpath.endswith("doc") or fpath.endswith("docx"):
               if needle in word2text(fpath):
                    yield fpath

for filename in search_word_in_path(r"C:\Users\<UserName>\Documents","some word"):
    print("Found 'some word' in %r"%filename)