2011-11-07 5 views
5

노르웨 이어의 Tkinter (Python 2.7)에 특수 문자 (æøå)가 포함되어있는 scrabblehelper 프로그램을 작성했습니다. 이는 내 단어 목록 (ordliste)에 특수 문자가 포함 된 단어가 있음을 의미합니다.UnicodeWarning : Tkinter의 특수 문자

내 함수 finnord (c *)를 실행하면 'cd'가 반환됩니다. 내 함수에 넣을 단어를 얻으려면 entry.get()을 사용하고 있습니다.

내 문제는 인 엔트리 (entry) .get()입니다. 로컬 코딩 UTF-8을 가지고 있지만, 내 입력란에 특수 문자를 쓰고 내 wordliste와 일치시킬 때 UniCodeError이 나옵니다.

다음은 제 출력물입니다.

Warning (from warnings module): 
    File "C:\pythonprog\scrabble\feud.py", line 46 
if s not in liste and s in ordliste: 
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode -  
interpreting them as being unequal 

난 내 쉘에서 쓰기 : 내 단어 목록에 ordinn.get() (항목)과 일치 할 수없는 이유

> ordinn.get() 
u'k\xf8**e' 
> ordinn.get().encode('utf-8') 
'k\xc3\xb8**e' 
> print ordinn.get() 
kø**e 
> print ordinn.get().encode('utf-8') 
kø**e 

누구나 알고?

답변

6

나는 오류이 방법을 재현 할 수 있습니다 :

% python 
Python 2.7.2+ (default, Oct 4 2011, 20:03:08) 
[GCC 4.6.1] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> 'k\xf8**e' in [u'k\xf8**e'] 
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal 
False 

그래서 아마도 sstr object이며, 그 반대의 경우도 마찬가지 (eryksun이 코멘트에 지적으로) liste 또는 ordlisteunicode을 포함, 또는. 해결책은 str object (대부분 utf-8 코덱)을 디코드하여 unicode이되도록하는 것입니다. 이 방법으로 문제가 해결되지 않으면

, 인쇄 및 unicode 모든 문자열을 변환하여 내가 문제를 방지 할 수 있다고 생각

print(repr(s)) 
print(repr(liste)) 
print(repr(ordliste)) 

의 출력을 게시하시기 바랍니다. 당신이 norsk.txt에서 ordliste을 생성

  1. , codecs.open('norsk.txt','r','utf-8') 사용 : 가능한 한 빨리 유니 코드로

    encoding = sys.stdin.encoding 
    with codecs.open('norsk.txt','r','utf-8') as fil: 
        ordliste = [line.rstrip(u'\n') for line in fil] 
    
  2. 변환 모든 사용자 입력 :

    def get_unicode(widget): 
        streng = widget.get() 
        try: 
         streng = streng.decode('utf-8') 
        except UnicodeEncodeError: 
         pass 
        return streng 
    

,691,363 (210)

그래서 아마도이 시도 :

import Tkinter as tk 
import tkMessageBox 
import codecs 
import itertools 
import sys 

alfabetet = (u"abcdefghijklmnopqrstuvwxyz" 
      u"\N{LATIN SMALL LETTER AE}" 
      u"\N{LATIN SMALL LETTER O WITH STROKE}" 
      u"\N{LATIN SMALL LETTER A WITH RING ABOVE}") 

encoding = sys.stdin.encoding 
with codecs.open('norsk.txt','r',encoding) as fil: 
    ordliste = set(line.rstrip(u'\n') for line in fil) 

def get_unicode(widget): 
    streng = widget.get() 
    if isinstance(streng,str): 
     streng = streng.decode('latin-1') 
    return streng 

def siord(): 
    alfa=lagtabell() 
    try: 
     streng = get_unicode(ordinn) 
     ordene=finnord(streng,alfa) 
     if len(ordene) == 0: 
      # There are no words that match 
      tkMessageBox.showinfo('Dessverre..','Det er ingen ord som passer...') 
     else: 
      # Done: The words that fit the pattern 
      tkMessageBox.showinfo('Ferdig', 
       'Ordene som passer er:\n'+ordene.encode('utf-8')) 
    except Exception as err: 
     # There has been a mistake .. Check your word 
     print(repr(err)) 
     tkMessageBox.showerror('ERROR','Det har skjedd en feil.. Sjekk ordet ditt.') 

def finnord(streng,alfa): 
    liste = set() 
    for substitution in itertools.permutations(alfa,streng.count(u'*')): 
     s = streng 
     for ch in substitution: 
      s = s.replace(u'*',ch,1) 
     if s in ordliste: 
      liste.add(s) 
    liste = [streng]+list(liste) 
    return u','.join(liste)+u'.' 

def lagtabell(): 
    tinbox = get_unicode(bokstinn) 
    if not tinbox.isalpha(): 
     alfa = alfabetet 
    else: 
     alfa = tinbox.lower() 
    return alfa 

root = tk.Tk() 
root.title('FeudHjelper av Martin Skow Røed') 
root.geometry('400x250+450+200') 
# root.iconbitmap('data/ikon.ico') 

skrift1 = tk.Label(root, 
       text = '''\ 
Velkommen til FeudHjelper. Skriv inn de bokstavene du har, og erstatt ukjente med *. 
F. eks: sl**ge 
Det er kun lov til å bruke tre stjerner, altså tre ukjente bokstaver.''', 
       font = ('Verdana',8), wraplength=350) 
skrift1.pack(pady = 5) 

ordinn = tk.StringVar(None) 
tekstboks = tk.Entry(root, textvariable = ordinn) 
tekstboks.pack(pady = 5) 

# What letters do you have? Eg "ahneki". Leave blank here if you want all the words. 
skrift2 = tk.Label(root, text = '''Hvilke bokstaver har du? F. eks "ahneki". La det være blankt her hvis du vil ha alle ordene.''', 
       font = ('Verdana',8), wraplength=350) 
skrift2.pack(pady = 10) 

bokstinn = tk.StringVar(None) 
tekstboks2 = tk.Entry(root, textvariable = bokstinn) 
tekstboks2.pack() 

knapp = tk.Button(text = 'Finn ord!', command = siord) 
knapp.pack(pady = 10) 
root.mainloop() 
+1

또는 단어 목록은 UTF-8입니다 (' 'K \ XC3 \ XB8 ** e'') 및 Entry.get'에서의()'hasn 유니 코드' 인코딩되었습니다. 동일한 오류가 발생합니다. – eryksun

+0

@eryksun : 네, 고마워요. – unutbu

+0

repr (%), s, liste 및 ordliste는 모두 원래 값과 동일한 값을 반환합니다. [링크] (http://pastebin.com/0MfJVLqf) ** 굵게 ** 여기 내 스크립트입니다. 나는 할 수있다 ' – Martol1ni