混合xml /文本解析python

教授85

我需要以这种丑陋的格式来解析一些日志文件(任何数量的纯文本标头,其中某些标头在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的开始和结束的软件包?

萨布吉·哈桑(Sabuj Hasan)

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章