【问题标题】:Make a dictionary from parsed data python从解析的数据python制作字典
【发布时间】:2014-09-26 00:38:45
【问题描述】:

我这里有这段代码,可以解析来自网络的 som 信息:

import lxml.html
from lxml.etree import XPath
import json



url = "http://gbgfotboll.se/information/?scr=table&ftid=51168"
date = '2014-09-27'
# use this in real mode: currentDate = (time.strftime("%Y-%m-%d"))
list = []
id = 0
score = ""
rows_xpath = XPath("//*[@id='content-primary']/table[3]/tbody/tr[td[1]/span/span//text()='%s']" % (date))
time_xpath = XPath("td[1]/span/span//text()[2]")
team_xpath = XPath("td[2]/a/text()")

html = lxml.html.parse(url)

for row in rows_xpath(html):
    time = time_xpath(row)[0].strip()
    team = team_xpath(row)[0]
    list.append("%d:"%id  + time + " " + team + " " + score)
    id += 1

print json.dumps(list)

哪个打印:

0:13:00 Romelanda UF - IK Virgo (empty score for now)
1:15:00 Kode IF - IK Kongah\xe4lla (empty score)
etc..

我的第一个子问题是,一些已解析的数据将包含字母“唓䔓ö”我将如何修复以便打印出正确的字母,如您在打印的结果(第二行)中看到的那样out "Kongah\xe4lla" 应该是 "Konghälla"

主要问题我如何将该列表转换为字典,以便最终的 json 输出如下:

{"id":"0", "time":"13:00", "teams":"Romelanda UF - IK Virgo", "score":"empty" }
etc...

谢谢!!!

【问题讨论】:

    标签: python json parsing dictionary


    【解决方案1】:

    对于您的第一个问题,\xe4 不是 ascii 字符,如果您想将其打印出来,可能您可以尝试使用一些似乎是“windows-1252”的编码对其进行解码。

    当我尝试这个时,它对我有用:

    a='\xe4'
    b=a.decode('windows-1252')
    print b
    

    对于第二个问题,只需将代码修改为:

    for i,row in enumerate(rows_xpath(html)):
        #
        #
        list.append({"id":str(i), "time":time, "teams":team, "score":score})
    

    而且我认为你并不想将你的列表命名为“list”,它是 python 的一种关键字~ 祝你好运。

    顺便说一下,枚举会自动生成索引,你仍然可以使用你的“id”,只是这样:

     list.append({"id":str(id), "time":time, "teams":team, "score":score})   
    

    【讨论】:

    • 非常感谢!这对我帮助很大。但是关于你的第一个答案。正如您所看到的,它解析来自网络的信息,所以我不知道这三个字母中的哪一个会在何时何地出现。每天都会解析新信息,那么我将如何制作每次解析和更正时都会检查的东西? @lisnb 还请注意,当涉及到字典时,您不能使用 .append。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 2016-06-09
    • 2016-11-24
    • 2018-10-30
    • 2021-08-26
    • 1970-01-01
    • 2017-03-28
    相关资源
    最近更新 更多