gpt4 book ai didi

python - 使用python逐行读取.trc文件并返回信息

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

我需要一些有关 python 代码的帮助来逐行读取 .trc 文件并从读取的行返回数据。

trc 文件示例:

<A> DATA1 </A>
<L size ="20">
<F4 size ="1">46.0</F4>
<F4 size ="1">47.1</F4>
<F4 size ="1">23.0</F4>
<F4 size ="1">17.45</F4>
<F4 size ="1">49.0</F4>
<F4 size ="1">50.0</F4>
<F4 size ="1">12.0</F4>
</L>
<A> DATA2 </A>
<L size ="20">
<F4 size ="1">12.0</F4>
<F4 size ="1">19.34</F4>
<F4 size ="1">23.0</F4>
<F4 size ="1">99.0</F4>
<F4 size ="1">0.11</F4>
<F4 size ="1">78.0</F4>
<F4 size ="1">12.0</F4>
</L>

输出应写入 Excel 表格内

预期输出:

DATA        DATA2
46.0 12.0
47.1 19.34
23.0 23.0
17.45 99.0
49.0 0.11
50.0 78.0
12.0 12.0

我是Python新手,希望有人能帮助我。

最佳答案

下面

import xml.etree.ElementTree as ET
from collections import defaultdict

trc = '''<r><A> DATA1 </A>
<L size ="20">
<F4 size ="1">46.0</F4>
<F4 size ="1">47.1</F4>
<F4 size ="1">23.0</F4>
<F4 size ="1">17.45</F4>
<F4 size ="1">49.0</F4>
<F4 size ="1">50.0</F4>
<F4 size ="1">12.0</F4>
</L>
<A> DATA2 </A>
<L size ="20">
<F4 size ="1">12.0</F4>
<F4 size ="1">19.34</F4>
<F4 size ="1">23.0</F4>
<F4 size ="1">99.0</F4>
<F4 size ="1">0.11</F4>
<F4 size ="1">78.0</F4>
<F4 size ="1">12.0</F4>
</L></r>'''

root = ET.fromstring(trc)
data = defaultdict(list)
l_list = root.findall('.//L')
for idx,l in enumerate(l_list,1):
key = 'DATA{}'.format(idx)
for f in l.findall('.//F4'):
data[key].append(f.text)
print('\t'.join(data.keys()))
for row in zip(*data.values()):
print('\t'.join(str(v) for v in row))

输出

DATA1   DATA2
46.0 12.0
47.1 19.34
23.0 23.0
17.45 99.0
49.0 0.11
50.0 78.0
12.0 12.0

关于python - 使用python逐行读取.trc文件并返回信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58361292/

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