2017-03-27 2 views
1

다음 코드의 경우; UnicodeEncodeError : 'ascii'코덱은 7의 위치에 u ' u2013'문자를 인코딩 할 수 없습니다.

phonenumbers = ['(209) 525-2987', '509-477-4598', None, '229-259–1234'] 
phoneCheck = re.compile('^[1-9]\d{2}-\d{3}-\d{4}$') 

for pn in phonenumbers: 
    print pn 
    if phoneCheck.match(str(pn)): 
     print 'Matched!' 
    else: 
     print 'Not Matched!' 

나는 결과에서이 오류가 나는 그것이 일치하지 표시되었다 그래서 나는이 문제를 해결 할 방법이 전화 번호에 사용되는 대시 잘못된 유형의 관계가 생각?

(209) 576-6546 
Not Matched! 
509-477-6726 
Not Matched! 
None 
Not Matched! 
229-259–9756 
Runtime error 
Traceback (most recent call last): 
    File "<string>", line 6, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 7: ordinal not in range(128) 
+0

이것은 유니 코드에 대한 일반적인 문제입니다. 지금까지 어떤 시도를 했습니까? http://stackoverflow.com/search?q=UnicodeEncodeError%3A+%27ascii%27+codec+can%27t+encode+character+u%27%5Cu2013%27+in+ –

+0

'u'\ u2013 '는 유니 코드 문자 및 아스키가 아닙니다 – Dadep

+0

나는 아무것도 시도하지 않았습니다. 이것은 위의 코드로 무엇을합니까? @DavidZemens 코드로 얻은 최초의 UnicodeEncodeError입니까? – Purplepeopleeater

답변

1

진단 내용이 정확합니다. (마지막 전화 번호의 두 번째 대시는 화려한 일종의 대시입니다. 워드 프로세서 나 스프레드 시트에서 전화 번호를 복사하여 붙여 넣으면됩니다.) ...

다음은 빠른 전화 번호입니다. 쉬운 방법 : 유니 코드 패키지를 설치하려면 다음을 수행하십시오.

import re 
import warnings 

import unidecode 

dash = u'\u2013' 
phonenumbers = ['(209) 525-2987', '509-477-4598', None, '229-259' + dash + '1234'] 
phoneCheck = re.compile('^[1-9]\d{2}-\d{3}-\d{4}$') 

# if you pass an ascii string into unidecode, it will complain, but still work. 
# Just catch the warnings. 
with warnings.catch_warnings(): 
    warnings.simplefilter("ignore") 

    for pn in phonenumbers: 
     print pn 

     # if pn is None, it's not a phone number (and None will cause unidecode 
     # to throw an error) 
     if pn and phoneCheck.match(unidecode.unidecode(pn)): 
      print 'Matched!' 
     else: 
      print 'Not Matched!' 
관련 문제