首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Python从XML中提取元素的所有属性

用Python从XML中提取元素的所有属性
EN

Stack Overflow用户
提问于 2019-10-21 09:03:12
回答 2查看 63关注 0票数 0

我有多个XML文件,其中包含类似于以下格式的tweet:

代码语言:javascript
复制
<tweet idtweet='xxxxxxx'> 
    <topic>#irony</topic> 
    <date>20171109T03:39</date> 
    <hashtag>#irony</hashtag> 
    <irony>1</irony> 
    <emoji>Laughing with tears</emoji> 
    <nbreponse>0</nbreponse> 
    <nbretweet>0</nbretweet> 
    <textbrut> Some text here <img class="Emoji Emoji--forText" src="source.png" draggable="false" alt="" title="Laughing with tears" aria-label="Emoji: Laughing with tears"></img> #irony </textbrut> 
    <text>Some text here #irony </text> 
</tweet>

创建文件的方式有问题( img的结束标记丢失了),所以我选择了关闭它,就像上面的例子一样。我知道在HTML中,您可以将它关闭为

代码语言:javascript
复制
<img **something here** /> 

但我不知道这是否适用于XML,因为我在任何地方都没有看到它。

我正在编写一个python代码,它提取主题和纯文本,但我也对img包含的所有属性感兴趣,我似乎无法做到这一点。以下是我迄今尝试过的:

代码语言:javascript
复制
top = []
txt = []
emj = []

for article in root:
    topic = article.find('.topic')
    textbrut = article.find('.textbrut')

    emoji = article.find('.img')
    everything = textbrut.attrib

    if topic is not None and textbrut is not None:
            top.append(topic.text)
            txt.append(textbrut.text)

            x = list(everything.items())
            emj.append(x)

任何帮助都将不胜感激。

EN

回答 2

Stack Overflow用户

发布于 2019-10-21 12:00:26

显然,元素有一些有用的方法(例如Element.iter()),它帮助递归地迭代它下面的所有子树(其子树、其子树、.)。因此,这是对我有效的解决方案:

代码语言:javascript
复制
for emoji in root.iter('img'):
    print(emoji.attrib)
    everything = emoji.attrib
    x = list(everything.items())
    new.append(x)

欲知更多细节,请在这里阅读。

票数 1
EN

Stack Overflow用户

发布于 2019-10-21 13:55:23

下面

代码语言:javascript
复制
import xml.etree.ElementTree as ET

xml = '''<t><tweet idtweet='xxxxxxx'> 
    <topic>#irony</topic> 
    <date>20171109T03:39</date> 
    <hashtag>#irony</hashtag> 
    <irony>1</irony> 
    <emoji>Laughing with tears</emoji> 
    <nbreponse>0</nbreponse> 
    <nbretweet>0</nbretweet> 
    <textbrut> Some text here <img class="Emoji Emoji--forText" src="source.png" draggable="false" alt="" title="Laughing with tears" aria-label="Emoji: Laughing with tears"></img> #irony </textbrut> 
    <text>Some text here #irony </text> 
</tweet></t>'''

root = ET.fromstring(xml)
data = []
for tweet in root.findall('.//tweet'):
    data.append({'topic': tweet.find('./topic').text, 'text': tweet.find('./text').text,
                 'img_attributes': tweet.find('.//img').attrib})
print(data)

输出

代码语言:javascript
复制
[{'topic': '#irony', 'text': 'Some text here #irony ', 'img_attributes': {'class': 'Emoji Emoji--forText', 'src': 'source.png', 'draggable': 'false', 'alt': '', 'title': 'Laughing with tears', 'aria-label': 'Emoji: Laughing with tears'}}]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58483006

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档