40

我一直在开发一个程序来从 Stack Overflow 中检索问题。直到昨天程序运行良好,但从今天开始我得到了错误

"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')
4

2 回答 2

66
于 2014-06-17T14:00:53.380 回答
3

I ran into this as well using Transifex API

response['source_string']

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

Fixed with 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")
于 2017-08-18T00:18:11.113 回答