2014-06-17 12 views
17

Tôi đã làm việc trên một chương trình để truy xuất các câu hỏi từ ngăn xếp tràn. Cho đến hôm qua chương trình đã hoạt động tốt, nhưng kể từ hôm nay tôi nhận được lỗiUnicodeEncodeError: 'ascii' codec không thể mã hóa ký tự u ' u201c' ở vị trí 34: thứ tự không nằm trong phạm vi (128)

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

Hiện tại câu hỏi đang được hiển thị nhưng dường như tôi không thể sao chép đầu ra sang tệp văn bản mới.

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') 
+0

Những dòng đang gây ra lỗi này? Ngoài ra, regex '[aA-zZ] +' sẽ không làm những gì bạn nghĩ. Bạn cần '[A-Za-z] +' hoặc '(? I) [A-Z] +'. –

+0

question.write (q.title) đang gây ra lỗi. –

+0

Tôi đang sử dụng ** [aA-zZ] + ** để chỉ trích xuất các từ và bỏ qua các số và ký tự đặc biệt. –

Trả lời

38

q.title là chuỗi Unicode. Khi viết nó vào một tập tin, bạn cần phải mã hóa nó trước, tốt nhất là mã hóa có khả năng Unicode hoàn toàn như UTF-8 (nếu không, Python sẽ mặc định sử dụng codec ASCII không hỗ trợ bất kỳ ký tự mã nào bên trên 127) .

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

nên khắc phục sự cố.

Nhân tiện, chương trình được truy cập vào ký tự (U+201C).

0

Tôi chạy vào này cũng sử dụng Transifex API

response['source_string']

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

cố định với 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") 
Các vấn đề liên quan