Py学习  »  Python

在python中,如何基于关键字提取txt文件的一部分?

Zeshan Fayyaz • 5 年前 • 1592 次点击  

假设有一个很大的文本文件,大约有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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54274
 
1592 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Daniel
Reply   •   1 楼
Daniel    5 年前

像这样的怎么样?

# 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>