gpt4 book ai didi

python - 混合 xml/文本解析 python

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:34 25 4
gpt4 key购买 nike

我需要解析一些这种丑陋格式的日志文件(任意数量的纯文本 header ,其中一些 header 在 xml 中获取附加数据):

[dd/mm/yy]:message_data
<starttag>
<some_field>some_value</some_field>
....
</starttag>
[dd/mm/yy]:message_data
[dd/mm/yy]:message_data
....

到目前为止我的方法是:

    message_text = None
for line in LOGFILE:

message_start_match = MESSAGE_START_RE.search(line)
if not message_start_match:
header_info = HEADER_RE.search(line)

if message_start_match:
message_text = line
continue
if message_text:
message_text += line

if MESSAGE_END_RE.search(line):
process_message_with_xml_parser(message_text, header_info)
message_text=None

哪里

MESSAGE_START_RE = re.compile(r"<starttag.*>)
MESSAGE_END_RE = re.compile(r"</starttag>)
header_info is a regex with named fields of the message

你知道更好的方法吗?

这种方法的问题是:我有点用正则表达式解析 xml(这是愚蠢的)。是否有任何包可以识别文件中 xml 的开头和结尾?

最佳答案

您仍然可以在丑陋的 xml 上使用 BeautifulSoup。这是一个例子:

from bs4 import BeautifulSoup

data = """[dd/mm/yy]:message_data
<starttag>
<some_field>some_value</some_field>
....
</starttag>
[dd/mm/yy]:message_data
[dd/mm/yy]:message_data"""

soup = BeautifulSoup(data);
starttag = soup.findAll("starttag")
for tag in starttag:
print tag.find("some_field").text
# => some_value

关于python - 混合 xml/文本解析 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22913251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com