如何使用 python 从这个 xml/txt 文件构建一个 sqlite 表? [英] How can I build an sqlite table from this xml/txt file using python?

查看:24
本文介绍了如何使用 python 从这个 xml/txt 文件构建一个 sqlite 表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 xml/txt 文件:

I have an xml/txt file like this:

<text id="32a45" language="ENG" date="2017-01-01" time="11:00" timezone="Eastern">

<s id="1">
foo
bar
</s>
<d>
11235
</d>

<text id="32a47" language="ENG" date="2017-01-05" time="1:00" timezone="Central">

<s id="2">
foo
bar
</s>
<d>
11235
</d>

<text id="32a48" language="ENG" date="2017-01-07" time="3:00" timezone="Pacific">

<s id="3">
foo
bar
</s>
<d>
11235
</d>

我想使用 python 构建如下所示的 sqlite 表:

I want to build an sqlite table like the following using python:

id  language    date        timezone    s           d

32a45   ENG     2017-01-01  Eastern     foo bar     11235
32a47   ENG     2017-01-05  Central     baz qux     11235
32a48   ENG     2017-01-07  Pacific     foo bar     11235

知道我该怎么做吗?我无法使用 xmltree 模块,因为原始文件中的 xml 标签被弄乱了.我真的很感激你的帮助.谢谢.

Any idea how can I do this? I cannot use xmltree module because the xml tags in the original file is messed up. I would really appreciate the help. Thanks.

我可以轻松地将每个文本作为列表中的列表.像这样:

I can easily take each text as a list inside a list. Like this:

['<text id="32a45" language="ENG" date="2017-01-01" time="11:00" timezone="Eastern">', '<text id="32a47" language="ENG" date="2017-01-05" time="1:00" timezone="Central">', '<text id="32a48" language="ENG" date="2017-01-07" time="3:00" timezone="Pacific">']

但我不知道如何分别从每个列表中获取 ID、语言等.

But I don't know how to take the id, language etc. from each list separately.

推荐答案

重定向自此处:

如何根据python中的字符串从列表中创建子列表?

import xml.etree.ElementTree as ET
import pandas as pd

strings = ['<text id="32a45" language="ENG" date="2017-01-01" time="11:00" timezone="Eastern">',
'<text id="32a47" language="ENG" date="2017-01-05" time="1:00" timezone="Central">',
'<text id="32a48" language="ENG" date="2017-01-07" time="3:00" timezone="Pacific">']

cols = ["id","language","date","time","timezone"]
data = [[ET.fromstring(string+"</text>").get(col) for col in cols] for string in strings]    
df = pd.DataFrame(data,columns=cols)

这篇关于如何使用 python 从这个 xml/txt 文件构建一个 sqlite 表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆