如何在python-3中分析PDF中的特定文本字符串?

问题描述 投票:0回答:1

我正在研究一些用于识别PDF文档中命名实体(NER)的代码。我当前的代码分三步工作。首先,它将PDF转换为文本字符串。其次,它标记文本。第三,它对文本进行分类。

现在,此代码对文本字符串中的每个标记(单词)进行分类。但是,我希望程序仅对文本的特定部分进行分类。该部分始终位于单词"Body""Classification"之间(对于那些熟悉格式的人,我正在分析LexisNexis文档)。我想知道是否有办法告诉程序仅对这两个词之间的文本进行分类?我已经阅读了几篇有关此问题的文章,但无法找到特定问题的答案。

我有一种感觉,我需要在"tokenized_text""classified_text"行之间插入用于标识特定字符串的行,但是我不确定是什么。感谢您的帮助!

#Import Programs for NER
import os
import PyPDF2
import nltk
import pandas

# NER tagger
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize

st = StanfordNERTagger('C:\\file_path\\english.all.3class.distsim.crf.ser.gz',
                       'C:\\file_path\\stanford-ner.jar',
                       encoding='utf-8')

destDirectory = file_path

#Tagging NERs
for file in os.listdir(destDirectory):
    pdf_file = open(destDirectory + '\\' + file, 'rb')
    read_pdf = PyPDF2.PdfFileReader(pdf_file)
    number_of_pages = read_pdf.getNumPages()
    text = ''
    for i in range(0,number_of_pages):
        page = read_pdf.getPage(i)
        page_content = page.extractText()
        text = text+page_content
    tokenized_text = word_tokenize(text)
    classified_text = st.tag(tokenized_text)

print(classified_text)

编辑:

这里是一个更简单的代码。注意,除非您下载了Stanford标记(St)并设置了文件位置,否则该程序将无法运行。

#Import Programs for NER
import os
import PyPDF2
import nltk
import pandas

# NER tagger
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize

st = StanfordNERTagger('C:\\file_path\\english.all.3class.distsim.crf.ser.gz',
                       'C:\\file_path\\stanford-ner.jar',
                       encoding='utf-8')

destDirectory = file_path

#Tagging NERs
for file in os.listdir(destDirectory):
    # Insert code here for reading in the PDFs
    text = 'Title Example Body This is an example line of text. Classification Language: English'
    tokenized_text = word_tokenize(text)
    classified_text = st.tag(tokenized_text)

print(classified_text)
python python-3.x text nltk text-classification
1个回答
0
投票

您可以使用如下所示的正则表达式来提取要标记的单词:

>>> import re
>>> s ='sample line Body WORD TO EXTRACT Classification'
>>> re.search(r'Body(.*?)Classification', s).group(1)
' WORD TO EXTRACT '

对于多次出现,您可以使用re.findall

© www.soinside.com 2019 - 2024. All rights reserved.