【问题标题】:I need to map keys to csv values that I read from an URL using Python 2.7我需要将键映射到使用 Python 2.7 从 URL 读取的 csv 值
【发布时间】:2017-11-13 17:56:30
【问题描述】:

我需要将键映射到我使用 Python 2.7 从 URL 读取的 csv 值。 将运行此 Python 脚本的目标计算机是运行 Raspbian 9(基于 Debian 9 的 Raspberry Pi 发行版)的 RaspberryPi 3。

我需要从太阳能逆变器(准确地说是 SAJ Sununo 3K-M 太阳能逆变器)读取一组不断变化的值,并将其映射到一组固定的字段名。

期望值的顺序与字段名的顺序完全相同,但它们需要相互映射。 URL 也是它所需要的

我已尝试读取这些值,并且可以成功读取这些值,但实际上我无法将这些值映射到变量以做一些有用的事情。

如果我读取 csv 值,我得到的响应示例如下:

['1', '4378', '998', '668', '69', '1842', '328', '1226', '336', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '65535', '992', '4999', '2364', '421', '65535', '65535', '65535', '65535', '3663', '348', '343', '2']

如果有人能破解我正在努力实现的目标,我将不胜感激。

我已经复制/粘贴了我目前在下面编写的代码。

#!/usr/bin/python
# This script reads the output of SAJ Solar Inverters and parses it so that it can be used in a meaningful way 
# Import libraries
import csv
import urllib2
import base64

def main():
    global username,password, responselist
username = 'USER-LOGIN'
password = 'USER-PASSWORD'
statusfieldnames = ['Statistics', 'Total_Generated', 'Total_Running Time', 'Today_Generated', 'Today_Running_Time', 'PV1_Voltage', 'PV1_Current', 'PV2_Voltage', 'PV2_Current', 'PV3_Voltage', 'PV3_Current', 'PV1_StrCurr1', 'PV1_StrCurr2', 'PV1_StrCurr3', 'PV1_StrCurr4', 'PV2_StrCurr1', 'PV2_StrCurr2', 'PV2_StrCurr3', 'PV2_StrCurr4', 'PV3_StrCurr1', 'PV3_StrCurr2', 'PV3_StrCurr3', 'PV3_StrCurr4', 'Grid-connected_Power', 'Grid-connected_Frequency', 'Line1_Voltage', 'Line1_Current', 'Line2_Voltage', 'Line2_Current', 'Line3_Voltage', 'Line3_Current', 'Bus_Voltage', 'Device_Temperature', 'CO2emission_Reduction', 'Other_Status']

request = urllib2.Request("http://IP-ADDRESS-OF-RPI3/status/status.php")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
response = urllib2.urlopen(request)
status = csv.reader(response, delimiter=",")

【问题讨论】:

    标签: python python-2.7 csv dictionary


    【解决方案1】:

    假设顺序和长度完全相同,您可以使用以下代码:

    valDict={}
    for f, v in zip(statusfieldnames, response):
        valDict[f] = v
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      相关资源
      最近更新 更多