2014-06-17 7 views
17

Ho lavorato a un programma per recuperare le domande dallo stack overflow. Fino a ieri il programma stava lavorando bene, ma dal momento che oggi sto ottenendo l'erroreUnicodeEncodeError: il codec 'ascii' non può codificare il carattere u ' u201c' nella posizione 34: ordinale non compreso nell'intervallo (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)" 

Attualmente vengono visualizzate le domande, ma mi sembra di essere in grado di copiare l'output in un nuovo file di testo.

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

Quale linea sta causando questo errore? Inoltre, la regex '[aA-zZ] +' non farà quello che pensi che faccia. Hai bisogno di '[A-Za-z] +' o '(? I) [A-Z] +'. –

+0

question.write (q.title) sta causando l'errore. –

+0

Sto usando ** [aA-zZ] + ** per estrarre solo parole e ignorando numeri e caratteri speciali. –

risposta

38

q.title è una stringa Unicode. Quando lo scrivi in ​​un file, devi prima codificarlo, preferibilmente una codifica pienamente compatibile con Unicode come UTF-8 (se non lo fai, Python utilizzerà il codec ASCII che non supporta alcun punto di codice carattere sopra 127) .

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

dovrebbe risolvere il problema.

A proposito, il programma è scattato sul carattere (U+201C).

0

mi sono imbattuto in questo pure usando Transifex API

response['source_string']

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

fisso con 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") 
Problemi correlati