运行Json时出现UnicodeEncodeError

时间:2017-02-18 19:41:42

标签: python json python-2.7

运行此测试脚本时出现Unicode错误。

import urllib
import json

movieTitle = "Bee Movie"
title = movieTitle.replace(" ", "+")
year = ""
omdbAPI = "http://www.omdbapi.com/?t={}&y={}&plot=short&r=json".format(
    title, year)
print (omdbAPI)
response = urllib.urlopen(omdbAPI)
data = json.loads(response.read())
valid_data = data["Response"]
print ("This data is: " + valid_data)

if valid_data == "True":
    print data["Title"]
    print data["Year"]
    print data["Plot"]
    print data["Rated"]
    print data["Released"]
    print data["Runtime"]
    print data["Genre"]
    print data["Director"]
    print data["Writer"]
    print data["Actors"]
    print data["Language"]
    print data["Country"]
    print data["Awards"]
    print data["Poster"]
    print data["Metascore"]
    print data["imdbRating"]
    print data["imdbVotes"]
    print data["imdbID"]
    print data["Type"]
    print data["Response"]
elif valid_data == "False":
    print ("This data is: " + valid_data)
else:
    raise ValueError("The information was not found")

错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 19: ordinal not in range(128)

我猜它是因为演员之间的接缝有一个é角色。

我发现我可以在.encode('utf8')之后放print data["Actors"],但它不像最聪明的事情那样接缝。 我的意思是一个随机的字母可能出现在演员的更多地方。在每个实例

之后,接缝变为奇数。.encode('utf8')

更新:

Traceback (most recent call last):
  File "/Volumes/postergren_projectDrive/Projekt/programmingSandbox/python/courses/udacity/Programming Foundations with Python/moveis/Advance/media.py", line 25, in <module>
    print data["Actors"]
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 19: ordinal not in range(128)
[Finished in 0.1s with exit code 1]
[shell_cmd: "python" -u "/Volumes/postergren_projectDrive/Projekt/programmingSandbox/python/courses/udacity/Programming Foundations with Python/moveis/Advance/media.py"]
[dir: /Volumes/postergren_projectDrive/Projekt/programmingSandbox/python/courses/udacity/Programming Foundations with Python/moveis/Advance]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

2 个答案:

答案 0 :(得分:1)

在代码开头尝试:

In [436]: np.einsum('ijk,km->jm',np.ones((2,3,3)),np.ones((3,4)))
Out[436]: 
array([[ 6.,  6.,  6.,  6.],
       [ 6.,  6.,  6.,  6.],
       [ 6.,  6.,  6.,  6.]])
In [437]: _.shape
Out[437]: (3, 4)

答案 1 :(得分:0)

你可以这样做:
for key in data.keys() data[key] = data[key].encode('utf8')