UnicodeEncodeError:' ascii'编解码器不能对字符u' \ u201c'进行编码。位置34:序数不在范围内(128)

时间:2014-06-17 13:17:08

标签: python python-2.7 pyscripter stackexchange-api

我一直在研究从堆栈溢出中检索问题的程序。直到昨天该程序工作正常,但从今天起我收到了错误

"Message    File Name   Line    Position    
Traceback               
<module>    C:\Users\DPT\Desktop\questions.py   13      
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 34: ordinal not in range(128)"

目前正在显示问题,但我似乎无法将输出复制到新的文本文件。

import sys
sys.path.append('.')
import stackexchange
so = stackexchange.Site(stackexchange.StackOverflow)
term= raw_input("Enter the keyword for Stack Exchange")
print 'Searching for %s...' % term,
sys.stdout.flush()
qs = so.search(intitle=term)
print '\r--- questions with "%s" in title ---' % (term)
for q in qs:
  print '%8d %s' % (q.id, q.title)
  with open('E:\questi.txt', 'a+') as question:
     question.write(q.title)

 time.sleep(10)
 with open('E:\questi.txt') as intxt:
   data = intxt.read()

regular = re.findall('[aA-zZ]+', data)
print(regular)

tokens = set(regular)

with open('D:\Dictionary.txt', 'r') as keywords:
  keyset = set(keywords.read().split())


with open('D:\Questionmatches.txt', 'w') as matches:
  for word in keyset:
    if word in tokens:
        matches.write(word + '\n')

2 个答案:

答案 0 :(得分:51)

q.title是一个Unicode字符串。将其写入文件时,您需要先对其进行编码,最好是完全支持Unicode的编码,例如UTF-8(如果您不这样做,Python将默认使用ASCII编解码器,不支持127)以上的任何字符代码点。

question.write(q.title.encode("utf-8"))

应该解决问题。

顺便说一下,该程序在角色U+201C)上绊倒了。

答案 1 :(得分:1)

我也使用Transifex API

遇到了这个问题

response['source_string']

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

已修复response['source_string'].encode("utf-8")

import requests

username = "api"
password = "PASSWORD"

AUTH = (username, password)

url = 'https://www.transifex.com/api/2/project/project-site/resource/name-of-resource/translation/en/strings/?details'

response = requests.get(url, auth=AUTH).json()

print response['key'], response['context']
print response['source_string'].encode("utf-8")