simplejson:加载西班牙语字符utf8

2024-10-01 17:36:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python的simplejson加载一些地理数据。在

<!-- language: lang-py -->
string = file("prCounties.txt","r").read().decode('utf-8')  
d = simplejson.loads(string)    

文本文件有一个颚化符,单词应该是añasco,而不是SimpleJson没有解析的u"A\xf1asco"。源是geoJson file from github

^{pr2}$

Python给出了错误simplejson.decoder.JSONDecodeError: Expecting object


我用来从GitHub加载以生成prCounties.txt的脚本。变量counties是与相关GEOjson数据的位置相关的字符串列表。在

很明显,这不是保存数据的正确方法:

<!-- language: lang-py -->
countyGeo = [ ]

for x in counties:      
    d = simplejson.loads(urllib.urlopen("https://raw.github.com/johan/world.geo.json/master/countries/USA/PR/%s" % (x)).read())         
    countyGeo += [ d["features"][0]]
    d["features"][0]=countyGeo  
file("prCounties.txt", "w").write(str(d))

编辑:在最后一行,我将str替换为simplejson.dumps。我想它现在编码正常了。 文件(“prCounties.txt“,”w“)。写(simplejson.dumps公司(d) )


Tags: 数据pygithubtxtlangreadstringlanguage
3条回答

输入文件不是有效的JSON。在"A\xf1asco"字符串之前有一个u,这是Python语法,而不是JSON语法。它应该是:

"name":"A\xf1asco",

这是有效的:

^{pr2}$

你必须去掉你的prCounties.txt文件(如前所述)。然后您可以使用这段代码,它可以很好地以simplejson.loads()功能:

import simplejson
string = file("prCounties.txt", "r").read().decode("string-escape")
string = unicode(string, "latin-1")
simplejson.loads(string)

这里有两个问题。第一个:

string = file("prCounties.txt","r").read().decode('utf-8')

你为什么要解码?JSON显式地接受UTF-8字符串。这是JSON定义的一部分。simplejson可以处理Unicode字符串这一事实使它的使用更加容易,但是它通过将它们编码回UTF-8来有效地处理它们,所以……为什么不首先就这样处理呢?在

更重要的是,你的数据来自哪里?如果prCounties.txt中有{},那么它不是JSON。你不能仅仅因为它们看起来相似,就把它们编码成一个标准,然后解码成完全不同的标准。在

例如,如果您使用了open('prCounties.txt', 'w').write(repr(my_dict)),那么您必须使用Python repr解析器(可能是ast.literal_eval,或者您必须自己编写一些东西)来读回它。在

或者,如果您想将数据解析为JSON,那么首先将其写为JSON。在


根据您的评论,数据是从https://raw.github.com/johan/world.geo.json/master/countries/USA/PR/Añ地理.json asco在

该URL的原始内容是:

^{pr2}$

您会注意到那里没有"name": u"Añasco"(或"name": u"A\xf1asco",或任何类似的东西)。您可以通过调用read来读取此内容—无需从UTF-8或其他任何格式解码它,只需将其传递给simplejson.loads即可正常工作:

$ curl -O https://raw.github.com/johan/world.geo.json/master/countries/USA/PR/Añasco.geo.json
$ cp Añasco.geo.json prCounties.txt
$ python
>>> import simplejson
>>> string = file("prCounties.txt","r").read()
>>> d = simplejson.loads(string)
>>> print d
{u'type': u'FeatureCollection', u'properties': {u'kind': u'state', u'state': u'PR'}, u'features': [{u'geometry': {u'type': u'MultiPolygon', u'coordinates': [[[[-67.122, 18.3239], [-67.0508, 18.3075], [-67.0398, 18.291], [-67.0837, 18.2527], [-67.122, 18.2417], [-67.1603, 18.2746], [-67.1877, 18.2691], [-67.2261, 18.2965], [-67.1822, 18.3129], [-67.1275, 18.3184]]]]}, u'type': u'Feature', u'properties': {u'kind': u'county', u'name': u'A\xf1asco', u'state': u'PR'}}]}

看,一点错误都没有。在

在某个地方,您对这些数据做了一些处理,将其转换为其他不是JSON的数据。我的猜测是,除了做一些不必要的额外的decodeencode调用之外,你还做了一个simplejson.loads,然后试图重新simplejson.loads你得到的repr。或者您已经用JSON编码了一个dict,其中充满了已经编码的JSON字符串。不管你做了什么,错误就出在那个代码,而不是你展示给我们的代码。在

最简单的解决方法可能是首先正确地生成prCounties.txt。每一行只有70多个下载行,可能需要2行bash或4行Python才能完成

相关问题 更多 >

    热门问题