简体   繁体   中英

Python encoding issue w/ ascii to utf-8

I'm currently running into an issue when trying to write data into a file from an api get request. the error is the following message: "UnicodeEncodeError: 'ascii' codec can't encode character u'\\xe2' in position 1: ordinal not in range(128)"

I know this means I must convert the text from ascii to utf-8, but I'm not sure how to do this. This is the code that I have so far

import urllib2
import json

def moviesearch(query):
  title = query
  api_key = ""
  f = open('movie_ID_name.txt', 'w')
  for i in range(1,15,1):
    api_key = "http://api.themoviedb.org/3/search/movie?api_key=b4a53d5c860f2d09852271d1278bec89&query="+title+"&page="+str(i)
    json_obj = urllib2.urlopen(api_key)
    json_obj.encode('utf-8')
    data = json.load(json_obj)
    for item in data['results']:
        f.write("<"+str(item['id'])+", "+str(item['title'])+'>\n')
f.close()

moviesearch("life")

When I run this I get the following error: AttributeError: addinfourl instance has no attribute 'encode'

What can I do to solve this? Thanks in advance!

Encoding/decoding only makes sense on things like byte strings or unicode strings. The strings in the data dictionary are Unicode, which is good, since this makes your life easy. Just encode the value as UTF-8:

import urllib2
import json

def moviesearch(query):
  title = query
  api_key = ""
  with open('movie_ID_name.txt', 'w') as f:
    for i in range(1,15,1):
      api_key = "http://api.themoviedb.org/3/search/movie?api_key=b4a53d5c860f2d09852271d1278bec89&query="+title+"&page="+str(i)
      json_obj = urllib2.urlopen(api_key)
      data = json.load(json_obj)
      for item in data['results']:
          f.write("<"+str(item['id'])+", "+item['title'].encode('utf-8')+'>\n')

moviesearch("life")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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