python – UnicodeWarning:Tkinter中的特殊字符
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – UnicodeWarning:Tkinter中的特殊字符,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4207字,纯文字阅读大概需要7分钟。
内容图文
![python – UnicodeWarning:Tkinter中的特殊字符](/upload/InfoBanner/zyjiaocheng/826/d631fa918f6048bfac5c6224a5688157.jpg)
我在Tkinter(Python 2.7)中编写了一个程序,这是挪威语中的一个scrabblehelper,包含一些特殊字符(æøå),这意味着我的wordlist(ordliste)包含带有特殊字符的单词.
当我运行我的函数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
当我写在我的shell中时:
> 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()(条目)与我的单词列表相匹配?
解决方法:
我可以这样重现错误:
% 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对象,而liste或ordliste包含unicode,或者(如eryksun在注释中指出的那样)反之亦然.解决方案是解码str对象(最有可能使用utf-8编解码器)以使它们成为unicode.
如果这没有帮助,请打印并发布输出
print(repr(s))
print(repr(liste))
print(repr(ordliste))
我相信通过将所有字符串转换为unicode可以避免这个问题.
>从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]
>尽快将所有用户输入转换为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()
内容总结
以上是互联网集市为您收集整理的python – UnicodeWarning:Tkinter中的特殊字符全部内容,希望文章能够帮你解决python – UnicodeWarning:Tkinter中的特殊字符所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。