Вложено XML в CSV с использованием Pandas, но открыто для предложений - PullRequest
0 голосов
/ 31 марта 2020

Я работаю с довольно вложенным XML файлом, который выглядит примерно так:

<?xml version="1.0" encoding="UTF-8"?>
 <OAI-PMH xmlns="http://www.openarchives.org/OAI/2.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd">
<responseDate>2019-06-20T10:26:55Z</responseDate>
<request verb="ListRecords" until="2019-06-18" metadataPrefix="arXiv" set="cs">http://export.arxiv.org/oai2</request>
<ListRecords>
<record>
<header>
 <identifier>oai:arXiv.org:0704.0002</identifier>
 <datestamp>2008-12-13</datestamp>
 <setSpec>cs</setSpec>
</header>
<metadata>
 <arXiv xmlns="http://arxiv.org/OAI/arXiv/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://arxiv.org/OAI/arXiv/ http://arxiv.org/OAI/arXiv.xsd">
 <id>0704.0002</id><created>2007-03-30</created><updated>2008-12-13</updated><authors><author><keyname>Streinu</keyname><forenames>Ileana</forenames></author><author><keyname>Theran</keyname><forenames>Louis</forenames></author></authors><title>Sparsity-certifying Graph Decompositions</title><categories>math.CO cs.CG</categories><comments>To appear in Graphs and Combinatorics</comments><msc-class>05C85; 05C70; 68R10; 05B35</msc-class><license>http://arxiv.org/licenses/nonexclusive-distrib/1.0/</license><abstract>  We describe a new algorithm, the $(k,\ell)$-pebble game with colors, and use
it obtain a characterization of the family of $(k,\ell)$-sparse graphs and
algorithmic solutions to a family of problems concerning tree decompositions of
graphs. Special instances of sparse graphs appear in rigidity theory and have
received increased attention in recent years. In particular, our colored
pebbles generalize and strengthen the previous results of Lee and Streinu and
give a new proof of the Tutte-Nash-Williams characterization of arboricity. We
also present a new decomposition that certifies sparsity based on the
$(k,\ell)$-pebble game with colors. Our work also exposes connections between
pebble game algorithms and previous sparse graph algorithms by Gabow, Gabow and
Westermann and Hendrickson.
</abstract></arXiv>
</metadata>
</record>

Я пробовал несколько способов извлечь эти данные в pandas DataFrame, чтобы я мог превратить его в плоский CSV. Форма CSV, которую я хотел бы, выглядела бы так:

    identifier, datestamp, setSpec, id, created, updated, authors, title, categories, comments, msc-class, license, abstract
    oai:arXiv.org:0704.0002, 2008-12-13, cs, 0704.0002, 2007-03-30, 2008-12-13, {keyname: [Streinu, Theran], forenames: [Ileana, Louis]}, Sparsity-certifying Graph Decompositions, math.CO cs.CG, To appear in Graphs and Combinatorics, 05C85; 05C70; 68R10; 05B35, some-license, We describe a new algorithm...

Я пробовал и lxml, и xml.etree.ElementTree. Я могу перечислить свои попытки ниже: Первая попытка: просто используя etree - iterparse файл. Этот метод дает мне все данные, но я не знаю, как я мог бы превратить это в сплющенный CSV

    for child in root.iter():
       print(child.tag, child.text)

Вторая попытка: указать точное значение от root до findall. Это дает мне 90%, но я не могу понять, как сохранить или на самом деле authors данные в этом формате.

    # getting metadata records
    data = []
    mData = root.findall("./{http://www.openarchives.org/OAI/2.0/}ListRecords/{http://www.openarchives.org/OAI/2.0/}record/{http://www.openarchives.org/OAI/2.0/}metadata/")

    # loop through metadata tags and append to empty set 
    for meta in mData:
        data.append({j.tag:j.text for j in list(meta)})

    # define the dataframe
    df = pd.DataFrame(data)

Что-нибудь поможет мне, я застрял на этом, и это мое впервые используя xml файлы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...