在Python中遍历.txt文件并分离为字符串

2024-09-30 01:21:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个Python脚本,它可以遍历一个.txt文件。文件长度一般为600-800行,格式如下:

==========
ID: 10001      Found:(4)
==========
MSG: ERR_ID  - ***ERROR*** _errortexthere_

==========
ID: 10002      Found:(26)
==========
MSG: ERR_ID  - ***ERROR*** _errortexthere_
line2
line3
line4
line5

==========
ID: 10003      Found:(15039)
==========
MSG: ERR_ID  - ***ERROR*** _errortexthere_
etc1
etc2
etc3

基本上,我想从'ID:'读取到'ID:'并将它们之间的所有文本存储在一个字符串中(或者数组、字典、你有的东西)。问题是,“ID:”之间的行数差别很大,因此按行号管理它们不会有多大帮助。我对Python相当陌生,对基本语法的熟悉程度不如其他语言。我已经做了大量的搜索,所以发现许多问题相似或接近我需要的,但不确切。任何帮助都将不胜感激。你知道吗


Tags: 文件txt脚本id格式msgerrorerr
2条回答

您应该逐行阅读并检查行中的第一个元素是否是ID

f = open('workfile', 'r')
for line in f:
    arr = line.split(" ")
    if(arr[0] == "ID:"):
       # do what you need too 

下面是一个非常简单的实现,它只检测以精确字符串“ID:”开头的行。它忽略空行和完全匹配==========的行。你知道吗

它将每个ID:后面的行保存到字典中,字典的键是ID字符串。你知道吗

from io import BytesIO
from pprint import pprint

infile = BytesIO("""
==========
ID: 10001      Found:(4)
==========
MSG: ERR_ID  - ***ERROR*** _errortexthere_

==========
ID: 10002      Found:(26)
==========
MSG: ERR_ID  - ***ERROR*** _errortexthere_
line2
line3
line4
line5
""")


buffer = ""
d = {}
id = None

for line in infile:
    if line.rstrip() in ("==========",""):
        # skip blank lines or delimiting lines
        pass
    elif line.startswith("ID: "):
        # save the buffer we've been collecting to the dictionary...
        if id is not None:        
            d[id] = buffer

        # ... and start collecting new lines
        id = line.split()[1]
        buffer = ""
    else:
        buffer += line
else:
    # save whatever lines are leftover after the last `ID:`
    if id is not None:
        d[id] = buffer

pprint(d)

输出:

{'10001': 'MSG: ERR_ID  - ***ERROR*** _errortexthere_\n',
 '10002': 'MSG: ERR_ID  - ***ERROR*** _errortexthere_\nline2\nline3\nline4\nline5\n'}

相关问题 更多 >

    热门问题