繁体   English   中英

python:修复写入 json 文件的数据中转义的 unicode 字符

[英]python: fix escaped unicode characters in data written to json file

我的程序有问题。 我访问谷歌地点 api 并获取一个 json,解析它并仅获取我感兴趣的值并将它们写入文件。 我对 google api 响应中的 unicode 字符有问题。 我正在使用在 Ubuntu 17.04 上运行的 python 2.7.13。

问题是 API 将字符串返回为:

索非亚王后国家艺术中心博物馆

有一个特殊字符:í

但是在文件中我发现了这个:

国家艺术中心博物馆

从请求中获取数据并使用 json.loads 后,我在 dict 中获得了 unicode 字符串,从那里开始它们与转义字符保持一致。 这是我的代码:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import urllib2
import json

def getPlaces(category, country, city, url, token):
    requestURL = url.replace("CATEGORY", category)
    requestURL = requestURL.replace("CITY", city)

    if not (token is None):
        requestURL = requestURL + "&pagetoken=" + token

    jsonData = urllib2.urlopen(requestURL).read()
    data = json.loads(jsonData)
    result = []

    for item in data["results"]:
        result.append(getRowData(item, country, category))
    if "next_page_token" in data:
        nextToken = data["next_page_token"]
        result = result + getPlaces(category, country, city, url, nextToken)
    return result

def getRowData(item, country, category):
    lsit = []
    name = item["name"]
    lat = item["geometry"]["location"]["lat"]
    lng = item["geometry"]["location"]["lng"]
    return [country, category, name, lat, lng]

# def listToStr(lst):
#   result = '[ '
#   if lst[0] is 

def_url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=CATEGORY+in+CITY&key=NOKEY:)"

attractions = getPlaces("museum", "Spain", "Madrid", def_url, None)

with open('data.txt', 'w') as outfile:
    json.dump(attractions, outfile)

我已经阅读了有关该主题的一些内容以及有关我正在使用的库的信息,但是我无法解决此问题。

也许你可以尝试 encode().decode() 因为"Sof\ía".encode().decode()工作正常。

在您的代码中,我会像这样更改getRowData函数:

def getRowData(item, country, category):
    lsit = []
    name = item["name"]
    lat = item["geometry"]["location"]["lat"]
    lng = item["geometry"]["location"]["lng"]
    return [country.encode().decode(), category.encode().decode(), 
            name.encode().decode(), lat, lng]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM