【问题标题】:Print the amount of times a word is in a pdf - python打印一个单词在pdf中的次数 - python
【发布时间】:2019-03-01 20:47:45
【问题描述】:

我在使用 pypdf 查找特定单词在 pdf 文件中出现的次数时遇到问题。

在我的代码中,它找到一个单词的次数,但每页只有一次。所以最大的是页数。单词“the”应该是700左右,但只显示30(页数为30)。

import PyPDF3
import re
def read_pdf(file,string):
    fils = file.split(".")
    print(fils[1])
    word = string
    if fils[1] == "pdf":
        pdfFileObj = open(file,"rb")
    # open the pdf file
        object = PyPDF3.PdfFileReader(file)
    # get number of pages
        NumPages = object.getNumPages()

    # define keyterms
        counter = 0
    # extract text and do the search
        for i in range(NumPages):
            PageObj = object.getPage(i)
            print("page " + str(i))
            Text = PageObj.extractText()
            #print(Text)
            if word in Text:
                print("The word is on this page")
                counter += 1
        print(word, "exists", counter, "times in the file")

你们能看到我做错了什么并帮助我吗?

谢谢:)

【问题讨论】:

  • 您将一页的文本读入Text 并检查是否为word in Text - 所以如果单词是the 和Text = "the the the the the the the the the ",则添加1。您需要计算 'the' 在文本中出现的频率 - 并添加计算的数量 - 而不是 1 。
  • python-finding-word-frequencies-of-list-of-words-in-text-file - 这可以处理查找单词列表的字数的更复杂的情况,但您可以简化给定的答案以满足您的需要

标签: python python-3.x pypdf


【解决方案1】:

您需要做的是将所有页面中的所有单词收集到一个列表中。
获得单词列表后,您可以使用 Counter 为您提供 pdf 中的单词及其编号

例子:

from collections import Counter

pdf_words = ['the','fox','the','jack']

counter = Counter(pdf_words)
print(counter)

输出:

Counter({'the': 2, 'fox': 1, 'jack': 1})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 2018-11-24
    • 1970-01-01
    相关资源
    最近更新 更多