Извлечь все атрибуты элемента из XML в Python - PullRequest
0 голосов
/ 21 октября 2019

У меня есть несколько XML-файлов, содержащих твиты в формате, аналогичном приведенному ниже:

<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)

Любая помощь будет принята с благодарностью.

Ответы [ 2 ]

1 голос
/ 21 октября 2019

Очевидно, у Element есть несколько полезных методов (таких как Element.iter () ), которые помогают рекурсивно выполнять итерацию по всему поддереву под ним (его дочерние элементы, их дочерние элементы, ...). Вот решение, которое сработало для меня:

for emoji in root.iter('img'):
    print(emoji.attrib)
    everything = emoji.attrib
    x = list(everything.items())
    new.append(x)

Подробнее читайте здесь.

0 голосов
/ 21 октября 2019

Ниже

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'}}]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...