我目前正在一个项目中,我想从PDF中提取文本,然后检查提取的文本中的单词之一是否出现在某个词典中。
如果是这样,我想给我们example.replace(file,x,y)将我文本中的单词替换为字典中的值。

我正在努力检查文本中的所有单词并将它们与字典自动比较的循环。目的是我不必自己键入“ old”和“ new”,但程序会检查文本中的所有单词,如果它在字典中找到一个单词,则“ old”应是文本中的单词,而“新”键的值。手动版本有效。

这是我的代码

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO

def convert_pdf_to_txt(path):

rsrcmgr = PDFResourceManager()

retstr = StringIO()
codec = 'utf-8'

laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = open(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos=set()

for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
    interpreter.process_page(page)

text = retstr.getvalue()

fp.close()
device.close()
retstr.close()
return text

dictionary = {"Die" : "Der", "Arbeitsfläche":"Platz"}


def convert(file, old, new):

translation = convert_pdf_to_txt(file).replace(old, new)
return translation

print(convert('mytest.pdf','Die' ,'Der'))


感谢帮助!

最佳答案

假设您能够阅读pdf文件。您可以使用以下命令将数据存储在列表中

list_voc = []

list_voc.extend(text.split())


现在使用一个简单的循环,您可以检查list的元素是否属于字典,如果存在,则将其替换。

indx=0
for i in pdf_vocab:
    if i in dictionary.keys():
        pdf_vocab[indx] = dictionary[i]
    indx = indx + 1


indx变量存储列表的索引,只要元素(或单词)在字典中,我们就可以在该特定索引处替换该单词。

关于python - 从PDF中提取文本并与字典进行比较,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52180315/

10-11 22:04
查看更多