UnicodeWarning:Tkinter中的特殊字符

5 投票
1 回答
8273 浏览
提问于 2025-04-17 05:47

我写了一个用Tkinter(Python 2.7)做的程序,这是一个挪威语的拼字游戏助手,里面有一些特殊字符(æøå),所以我的单词列表(ordliste)里也包含这些特殊字符的单词。

当我运行我的函数finnord(c*)时,它返回的是'cd'。我用entry.get()来获取输入的单词,然后放到我的函数里。

我遇到的问题是编码方面的。我的本地编码是UTF-8,但是当我在输入框里写入任何特殊字符并尝试与我的单词列表匹配时,就会出现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()
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

有没有人知道为什么我不能把ordinn.get()(输入)和我的单词列表匹配起来呢?

1 个回答

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

所以可能 s 是一个 str 对象,而 listeordliste 包含的是 unicode,或者(正如 eryksun 在评论中提到的)反过来也有可能。解决办法是将 str 对象 解码(很可能使用 utf-8 编码),这样它们就变成 unicode 了。

如果这样还不行,请打印并发布以下内容的输出:

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

我认为可以通过将所有字符串转换为 unicode 来避免这个问题。

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

撰写回答