2011-11-07 9 views
5

NorwegianのスクラブルヘルパーであるTkinter(Python 2.7)に特殊文字(æøå)を含むプログラムが書かれています。これは、私のワードリスト(ordliste)に特殊文字を含む単語が含まれていることを意味します。UnicodeWarning:Tkinterの特殊文字

私は私の関数finnord(C *)を実行すると、それは 'CD' を返します。私はentry.get()を使用して、自分の機能に入れる言葉を得ています。

私の問題はエンコーディングentry.getの()です。私は地元のUTF-8をコーディングしているが、私は私のentryboxに特殊文字を書いて、私の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

Iエラーをこのように再生することができる:

% 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 

ので、おそらくその逆(eryksunコメントで指摘したように)sstr objectあり、listeまたはordlisteunicodeを含有する、または。解決策は、それらunicode作るために(utf-8コーデックで最も可能性が高い)str object Sをデコードすることです。それでも解決しない場合は

、プリントアウトしてunicodeにすべての文字列を変換することによって、私は、問題を回避することができると信じて

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

の出力を投稿してください。

  1. あなたはnorsk.txtからordlisteを生成し、 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. できるだけ早くUnicodeにすべてのユーザー入力を変換します

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

ので、おそらくこれを試してみてください。

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'からS() 'hasnのUnicodeです'エンコードされています。同じエラーが発生します。 – eryksun

+0

@eryksun:はい、ありがとうございます。 – unutbu

+0

のrepr(%)、S、LISTEとordliste全てが元と同じ値を返します。 [リンク](http://pastebin.com/0MfJVLqf)**太字**はここに私のスクリプトです。コメントをありがとう:私は」 – Martol1ni