合并字典并作为输出传递给另一个函数

时间:2017-04-23 09:36:05

标签: python xml web-scraping

我正在学习python和编码。我正在尝试一个网络报废示例。我从网站下载货币兑换数据,我想计算50天内每种货币的平均汇率。问题是我无法做到以下几点。

我从第一个函数得到结果,该函数应该是字典形式,然后将这些字典作为参数传递给另一个函数,并对这些值进行平均。我无法将正确的dict值传递给另一个函数。 我的代码如下

import os 
import webbrowser
import requests as rq
import sys
from bs4 import BeautifulSoup
from xml.etree import ElementTree as ET


def saveData(path, date):
    session = rq.session()
    url = 'https://www.bnm.md/en/official_exchange_rates?get_xml=1&date=' + date
    datastore = session.get(url)
    with open(path, 'wb') as f:
         f.write(datastore.content)
    data = ET.fromstring(datastore.content)
    '''
    elements = {}
    for element in data.iter():
        if element.tag in ('Name', 'Value'):
            elements[element.tag] = element.text
            print 'elements:', elements
    # Here I want to combine those all dictionaries in variable so that i can pass it as argument to another function
    return elements
    '''
# i replace the above triple quote code with the following below code
    elements = {}
    for tag, text in data.items():
        if tag in ('Name', 'Value'):
            elements.setdefault(tag, [])
            elements[tag].append(text)
    return elements    

def computeAverage(elements):  # I want to pass function saveData() results who are in dictioanry form to this function but I am unable to solve this issue.
    print elements

def main():
    dates = ['20.04.2016', '21.04.2016', '22.04.2016']
    paths = []
    for date in dates:
        path = '/home/robbin/Desktop/webscrap/{}.xml'.format(date)
        paths.append(path)
    data3 = {}
    for path, date in zip(paths, dates):
        data2 = saveData(path, date)
        print 'data2: ', data2
        for k, v in data2.items():
            data3.setdefault(k, [])
            data3[k].append(v)
         print 'data3: ', data3
    computeAverage(data3)



if __name__ == '__main__':
     main()

此外,我将saveData()函数的结果作为这样的字典获取,并且它重复下一个项目的每个字典也是错误的。

elements:  {'Name': 'Euro'}
elements:  {'Name': 'Euro', 'Value': '22.4023'}
elements:  {'Name': 'US Dollar', 'Value': '22.4023'}
elements:  {'Name': 'US Dollar', 'Value': '19.7707'}
elements:  {'Name': 'Russian Ruble', 'Value': '19.7707'}
elements:  {'Name': 'Russian Ruble', 'Value': '0.3014'}
elements:  {'Name': 'Romanian Leu', 'Value': '0.3014'}
elements:  {'Name': 'Romanian Leu', 'Value': '4.9988'}

同样我试图得到这样的结果却失败了

elements: {'Name': 'Euro', 'Value': '22.4023'}
elements: {'Name': 'US Dollar', 'Value': '19.7707'}
elements: {'Name': 'Russian Ruble', 'Value': '0.3014'}
elements: {'Name': 'Romanian Leu', 'Value': '4.9988'} 

更新:-------------

    elements = []
    for element in data.iter():
        if element.tag in ('Name', 'Value'):
            elements.append(element.text)
            # print 'elements: ', elements
    return elements

并在主函数()中制作

for path, date in zip(paths, dates):
        data = saveData(path, date)
        # print 'data from main: ', data
        computeAverage(data)

输出"打印'数据来自main:',data"看起来像这样

['Euro', '22.4023', 'US Dollar', '19.7707', 'Russian Ruble', '0.3014', 'Romanian Leu', '4.9988',.........'Special Drawing Rights', '27.8688']
['Euro', '22.4408', 'US Dollar', '19.7421', 'Russian Ruble', '0.3007', 'Romanian Leu', '5.0012',.....'Special Drawing Rights', '27.8606']

我是编码的新手,如果有人帮我解决这两个问题。我真的很感激。

2 个答案:

答案 0 :(得分:1)

首先,我同意@Prakhar Verma。 其次,你没有清楚地提到你想要的东西。但是我可以假设你想要合并你从' saveData'中获得的数据。功能,然后计算平均值。所以,这是缺少的代码。

data3 = {}
for path, date in zip(paths, dates):
    data2 = saveData(path, date)
    for k, v in data2.items():
        # you can move this line after declaring the data3 dict if keys returned by saveData are fixed i.e. name, value
        data3.setdefault(k, [])
        data3[k].append(v)

computeAverage(data3)

更新到saveData函数:

elements = {}
for tag, text in data.items():
    if tag in ('Name', 'Value'):
        elements.setdefault(tag, [])
        elements[tag].append(text)

=============================================== ====

更新2:

def saveData(path, date):
    #session = rq.session()
    url = 'https://www.bnm.md/en/official_exchange_rates?get_xml=1&date=' + date
    datastore = rq.get(url)
    with open(path, 'wb') as f:
        f.write(datastore.content)
    data = ET.fromstring(datastore.content)

    # i replace the above triple quote code with the following below code
    elements = {}
    for element in data.iter():
        tag = element.tag
        text = element.text
        if tag in ('Name', 'Value'):
            elements.setdefault(tag, [])
            elements[tag].append(text)
    return elements

def main():
    dates = ['20.03.2016', '21.03.2016', '22.03.2016']
    paths = []
    for date in dates:
        #please edit this
        path = '{}.xml'.format(date)
        paths.append(path)
    data3 = {}
    for path, date in zip(paths, dates):
        data2 = saveData(path, date)
        for k, v in data2.items():
            data3.setdefault(k, [])
            data3[k].append(v)
    computeAverage(data3)

答案 1 :(得分:-1)

'saveData'函数返回数据但您没有将其保存在任何变量中。因此,您需要做的是在从“saveData”函数返回数据时保存数据,然后将其作为参数发送到“computeAverage”函数。

请仔细阅读编码基础知识并遵循任何编程教程。 :)