【问题标题】:Request XML file from URL and save as CSV using python从 URL 请求 XML 文件并使用 python 保存为 CSV
【发布时间】:2018-11-20 16:42:13
【问题描述】:

我是 python 编码的新手,我想从服务器获取 XML 文件,解析它并保存到 csv 文件。

2 部分没问题,我可以获取文件并对其进行解析,但另存为 csv 存在问题。

代码:

import requests
import numpy as np

hu = requests.get('https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml', stream=True)
from xml.etree import ElementTree as ET
tree = ET.parse(hu.raw)
root = tree.getroot()
namespaces = {'ex': 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref'}
for cube in root.findall('.//ex:Cube[@currency]', namespaces=namespaces):
    np.savetxt('data.csv', (cube.attrib['currency'], cube.attrib['rate']), delimiter=',')   

我得到的错误是:数组 dtype 和格式说明符不匹配。 这可能意味着我获取数据并尝试将其保存为数组,但出现不匹配。 但我不确定如何解决问题并且不匹配。

谢谢

【问题讨论】:

    标签: python xml csv


    【解决方案1】:

    docs 开始,np.savetext 中的第二个参数应该是 大小相等的数组中的 tuple。您提供的是字符串:

    >>> x = y = z = np.arange(0.0,5.0,1.0)
    >>> np.savetxt('test.out', x, delimiter=',')   # X is an array
    >>> np.savetxt('test.out', (x,y,z))   # x,y,z equal sized 1D arrays
    >>> np.savetxt('test.out', x, fmt='%1.4e')   # use exponential notation
    

    您需要将 所有 concurrencyrate 值收集到数组中,然后另存为 csv:

    concurrency, rate = [], []
    for cube in root.findall('.//ex:Cube[@currency]', namespaces=namespaces):
        concurrency.append(cube.attrib['concurrency'])
        rate.append(cube.attrib['rate'])
    
    np.savetext('file.csv', (concurrency, rate), delimeter='c')
    

    【讨论】:

    • 如何将所有货币和汇率值收集到数组中?请问如何从代码的第一部分填充数组?或者有没有办法在这种情况下根本不使用数组?只是为了获取数据并填写文件?
    • @bennes 看看for 循环中发生了什么。运行代码,你会看到发生了什么
    猜你喜欢
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2016-01-08
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多