在docx文件中查找特定单词

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

我正在进行小组作业,以读取docx文件,然后在其右侧直接输出单词'carrier'或'carriers'。我们收到的输出仅是文档中82个单词携带者提及的26个。我更喜欢建议而不是什么原因。我的直觉是,它与For循环有关。

from docx import Document

emptyString = {}
tupl = ()
doc = Document('Interstate Commerce Act.docx')

for i ,paragraph in enumerate(doc.paragraphs):
text = paragraph.text
text = text.split()
#text = text.lower()

    if 'carrier' in text:
        next = text.index('carrier') + 1
        now = text.index('carrier')
        #print(text[now], text[next]) 
        tupl = (text[now], text[next])
        emptyString[i] = tupl

    if 'carriers' in text:
        next = text.index('carriers') + 1
        now = text.index('carriers')
        #print(text[now], text[next])
        tupl = (text[now], text[next])
        emptyString[i] = tupl

    if 'Carriers' in text:
        next = text.index('Carriers') + 1
        now = text.index('Carriers')
        #print(text[now], text[next])
        tupl = (text[now], text[next])
        emptyString[i] = tupl

    if 'Carrier' in text:
        next = text.index('Carrier') + 1
        now = text.index('Carrier')
        #print(text[now], text[next])
        tupl = (text[now], text[next])   
        emptyString[i] = tupl

print(emptyString)
python enumeration python-docx
1个回答
0
投票

您的text = text.split()行将导致某些项目被“隐藏”。例如,“承运人是承运人”。将产生单词列表:

["The", "carrier", "is", "a", "Carrier."]

由于最后一项是“运营商”。而不是“运营商”,则无法通过“完全匹配”测试找到。

也许最好按单词拆分,然后检查小写版本includes“ carrier”:

words = text.split()
for i, word in enumerate(words):
    if "carrier" in word.lower():
        print("word %d is a match" % i)

使用小写字母比较避免了对所有大小写变体进行单独测试。

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