Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python解析许多xml对象并将它们写入文本文件(csv、tab del等)_Python_Xml_Csv_Beautifulsoup - Fatal编程技术网

使用python解析许多xml对象并将它们写入文本文件(csv、tab del等)

使用python解析许多xml对象并将它们写入文本文件(csv、tab del等),python,xml,csv,beautifulsoup,Python,Xml,Csv,Beautifulsoup,我有许多以下格式的XML对象: <GetSingleItemResponse xmlns="urn:ebay:apis:eBLBaseComponents"> <Timestamp>2012-10-25T03:09:50.817Z</Timestamp> <Ack>Success</Ack> <Build>E795_CORE_BUNDLED_15430047_R1</Build> <Vers

我有许多以下格式的XML对象:

<GetSingleItemResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2012-10-25T03:09:50.817Z</Timestamp>
  <Ack>Success</Ack>
  <Build>E795_CORE_BUNDLED_15430047_R1</Build>
  <Version>795</Version>
  <Item>
     <Description>...</Description>
     <ItemID>330810813385</ItemID>
     <EndTime>2012-10-25T04:32:37.000Z</EndTime>
     <Location>Paypal Prefered</Location>
     <GalleryURL>...</GalleryURL>
     <PictureURL>...</PictureURL>
     <PictureURL>...</PictureURL>
     <PrimaryCategoryID>177</PrimaryCategoryID>
     <PrimaryCategoryName>
     Computers/Tablets & Networking:Laptops & Netbooks:PC Laptops & Netbooks
     </PrimaryCategoryName>
     <BidCount>2</BidCount>
     <ConvertedCurrentPrice currencyID="USD">294.99</ConvertedCurrentPrice>
     <ListingStatus>Active</ListingStatus>
     <TimeLeft>PT1H22M47S</TimeLeft>
     <Title>
     HP Compaq ZD8000 3800Mhz Full Loaded Ready to go, nice unit & super fast Laptop
     </Title>
     <ShippingCostSummary>
     <ShippingServiceCost currencyID="USD">23.99</ShippingServiceCost>
     <ShippingType>Flat</ShippingType>
     <ListedShippingServiceCost currencyID="USD">23.99</ListedShippingServiceCost>
     </ShippingCostSummary>
     <ItemSpecifics>
        <NameValueList>
           <Name>Operating System</Name>
           <Value>Windows XP Professional</Value>
        </NameValueList>
        <NameValueList>
           <Name>Screen Size</Name>
           <Value>17.0</Value>
        </NameValueList>
        <NameValueList>
           <Name>Processor Type</Name>
           <Value>Intel Pentium 4 HT</Value>
        </NameValueList>
     </ItemSpecifics>
     <Country>US</Country>
     <AutoPay>false</AutoPay>
     <ConditionID>2500</ConditionID>
     <ConditionDisplayName>Seller refurbished</ConditionDisplayName>
   </Item>
</GetSingleItemResponse>

2012-10-25T03:09:50.817Z
成功
E795_核心_捆绑_15430047_R1
795
...
330810813385
2012-10-25T04:32:37.000Z
贝宝更喜欢
...
...
...
177
计算机/平板电脑和网络:笔记本电脑和上网本:PC笔记本电脑和上网本
2.
294.99
活跃的
PT1H22M47S
HP Compaq ZD8000 3800Mhz全负荷即用型、小巧的设备和超高速笔记本电脑
23.99
平的
23.99
操作系统
Windows XP专业版
屏幕大小
17
处理器类型
英特尔奔腾4 HT
美国
假的
2500
卖方翻新
对于每个xml对象,我希望获得所有项目标记,例如itemid、endtime等。。还有所有特定于项目的标记,如操作系统、屏幕大小等。我想将每个xml对象的标记保存到内存中,并保存到适当的数据结构(对象)中。最后,我想将所有xml对象的所有信息写入csv文件

困难在于,我事先不知道csv文件的列(标题)是什么。对于第一个xml对象,我将创建与项和项细节组合的子标签数量相同的列

然后,随着新项目的新列出现,我会添加越来越多的列,为以前没有出现的列添加NAs

我正在寻找有关如何处理xml对象、转换(保存)xml对象的数据结构以及如何将所有最终处理的xml数据写入csv文件的建议


谢谢。

对于csv中的每一行,您应该创建一个字典。解析xml时,应该为代码段中的每个
填充此词典。当您这样做时,您应该保留一组键,即列。。。这样,在文件末尾,您将知道有多少列及其标题

下面是如何实现这一点的一个小片段(如果数据适合内存),我将使用BeautifulSoup,因为您在标记中提到了它,它非常棒:

import sys
import csv

from BeautifulSoup import BeautifulSoup as Soup

doc = Soup(xml_string)
data = []
cols = set()
for item in doc.findAll('item'):
    d = {}
    for sub in item:
        if hasattr(sub, 'name'):
            d[sub.name] = sub.text
    data.append(d)
    cols = cols.union(d.keys())

cw = csv.writer(sys.stdout)
cw.writerow(cols)
for row in data:
    cw.writerow([row.get(k, 'N/A') for k in cols])
请注意,此解决方案假定您的键是唯一的,但在您的示例中,该项有两个图片URL,如果您希望两者都显示,则可能(因为没有什么是不可能的),只是稍微复杂一点


如果数据不适合内存,您将需要执行两个过程,第一个过程收集密钥,第二个过程打印csv。。。注意,您应该用另一个类似于本例的解析器替换BeautifulSoup,因为数据不适合内存

谢谢!这就是我所说的对我的问题的优雅而好的解决方案。@Dnaiel如果这个答案解决了你的问题,你应该接受它。@Pykler刚刚测试了它,效果很好。作为补充,csv是个坏主意,tab delimited是一种更好的格式,因为每个标记中的文本可能也有逗号…@Dnaiel您可以在csv中放置逗号。。。python库通过在必要时使用双引号很好地处理了这个问题。。。如果您确实需要tsv,则可以将csv编写器配置为使用