我有多个XML文件,其中包含类似于以下格式的tweet:
<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中,您可以将它关闭为
<img **something here** /> 但我不知道这是否适用于XML,因为我在任何地方都没有看到它。
我正在编写一个python代码,它提取主题和纯文本,但我也对img包含的所有属性感兴趣,我似乎无法做到这一点。以下是我迄今尝试过的:
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)任何帮助都将不胜感激。
发布于 2019-10-21 12:00:26
显然,元素有一些有用的方法(例如Element.iter()),它帮助递归地迭代它下面的所有子树(其子树、其子树、.)。因此,这是对我有效的解决方案:
for emoji in root.iter('img'):
print(emoji.attrib)
everything = emoji.attrib
x = list(everything.items())
new.append(x)发布于 2019-10-21 13:55:23
下面
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)输出
[{'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'}}]https://stackoverflow.com/questions/58483006
复制相似问题