gpt4 book ai didi

python - 解析带有标签的Python文本文件

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

我正在使用 python 解析一个 300 页的文档,我需要找出 ThisVal 元素后面的 Response 元素的属性值。 Response 元素在多个点用于 differentVals,因此我需要找出 Response elements< 中的内容 找到 ThisVal 元素后的属性值。

如果有帮助的话,标记对于 ThisVal 是唯一的,但在每个文档中都不同。

11:44:49 <ThisVal Token="5" />
11:44:49 <Response Token="5" Code="123123" elements="x.one,x.two,x.three,x.four,x.five,x.six,x.seven" />

最佳答案

您是否考虑过使用 pyparsing ?我发现它对于此类事情非常有用。以下是我尝试解决您的问题的尝试。

import pyparsing as pp

document = """11:44:49 <ThisVal Token="5" />
11:44:49 <Response Token="5" Code="123123" elements="x.one,x.two,x.three,x.four,x.five,x.six,x.seven" />
"""

num = pp.Word(pp.nums)
colon = ":"

start = pp.Suppress("<")
end = pp.Suppress("/>")
eq = pp.Suppress("=")

tag_name = pp.Word(pp.alphas)("tag_name")

value = pp.QuotedString("\"")

timestamp = pp.Suppress(num + colon + num + colon + num)
other_attr = pp.Group(pp.Word(pp.alphas) + eq + value)

tag = start + tag_name + pp.ZeroOrMore(other_attr)("attr") + end

tag_line = timestamp + tag

thisval_found = False

for line in document.splitlines():

result = tag_line.parseString(line)
print("Tag: {}\nAttributes: {}\n".format(result.tag_name, result.attr))

if thisval_found and tag_name == "Response":
for a in result.attr:
if a[0] == "elements":
print("FOUND: {}".format(a[1]))

thisval_found = result.tag_name == "ThisVal"

关于python - 解析带有标签的Python文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24250515/

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