【问题标题】:How to extract a portion of a txt file based on a keyword, in python?如何在python中根据关键字提取txt文件的一部分?
【发布时间】:2020-02-08 05:16:39
【问题描述】:

给定一个包含约 5000 个 HTML 文档的非常大的文本文件。我正在尝试“搜索”特定 DOCNO 的文本文件并打印文件的所有行,直到遇到下一个 </DOC> 标记。

文本文件大致如下:

<DOC>
<DOCNO>abc4567890</DOCNO>
contents 
more contents
<BODY> 
even more contents 
</BODY>
</DOC> 
... repeated roughly 5000 times for different DOC NO's

我正在寻找以下输出:

contents 
more contents
<BODY> 
even more contents 
</BODY>
</DOC> 

这是我一直在尝试实现的:

doc_string = "abc4567890"

with open('myfile.txt', encoding = "utf8") as f:
    for item in f.readlines():
        if "</DOCNO>" in item:
                ID = (item [ item.find("<DOCNO>")+len("<DOCNO>") : ])
                if (ID[0:9] == doc_string):
                    print (item)
                    if "</DOC>" in item:
                       break

但是,作为输出,我得到:

<DOCNO>abc4567890</DOCNO>

【问题讨论】:

    标签: python tags extract


    【解决方案1】:

    这样的事情怎么样?

    # initialize variables:
    lines = []
    read_lines = False
    
    with open('file.txt', 'r') as file:
    
        # iterate over each line:    
        for line in file.readlines():
    
            # append line to lines list:
            if read_lines: lines.append(line)
    
            # set read_lines to True:
            if '<DOCNO>abc4567890</DOCNO>' in line: read_lines = True
    
            # set read_lines to Flase:
            if '</DOC>' in line: read_lines = False
    
    
    # print each line:
    for line in lines:
        print(line, end='')
    

    根据您的输入,它将输出:

    contents 
    more contents
    <BODY> 
    even more contents 
    </BODY>
    </DOC> 
    

    【讨论】:

    • 这会遍历整个文件并打印和之间的每一行。但是,我只想对具有特定 DOCNO 的 1 个文档执行此操作。该文件由约 5000 个 DOCNO 组成
    • 感谢您的澄清。您可以更改将 read_lines 设置为 true 的条件,并在阅读完毕后中断循环。我已经更新了我的答案以反映这一点。
    • 对几个 DOCNO 尝试此代码,此代码仅适用于第一个 DOCNO。对于其他人,它不打印任何内容
    • 好的,那么在这种情况下,我们可以删除 break 语句并返回将 read_line 设置为 False。我已经编辑了我的答案以反映这一点。
    猜你喜欢
    • 2022-01-23
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    相关资源
    最近更新 更多