【问题标题】:Search folders and subfolders for a string within all Word and PDF files在所有 Word 和 PDF 文件中搜索文件夹和子文件夹中的字符串
【发布时间】:2017-07-18 18:10:33
【问题描述】:

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

【问题讨论】:

  • 没有真正的理由再使用 Python 2 而不是 Python 3,我建议您切换。是的,有可能做到这一点。不过,SO 不是代码编写服务。
  • 这里的白色标记包是一些软件还没有使用python3的原因py3readiness.org

标签: python string pdf ms-word subdirectory


【解决方案1】:

这是一个如何在文件中搜索单词的示例:

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,除非您可以先将它们转换为文本文件,否则将更加困难。

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

【讨论】:

    【解决方案2】:
    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)
    

    我猜......我把一些工作留给你作为 OP 来解决

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      相关资源
      最近更新 更多