[英]Comparing user input unicode strings in Python 2.7
將用戶輸入的字符串與另一個字符串進行比較的最佳方法是什么?
例如:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
user_input = raw_input("Please, write árido: ").decode("utf8")
if u"árido" == user_input:
print "OK"
else:
print "FALSE"
編輯:
這個
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from unicodedata import normalize
import sys
uinput2 = "árbol"
uinput = raw_input("type árbol: ")
print "Encoding %s" % sys.stdout.encoding
print "User Input \t\tProgram Input"
print "-"*50
print "%s \t\t\t%s \t(raw value)" % (uinput, uinput2)
print "%s \t\t\t%s \t(unicode(value))" % (unicode(uinput), unicode(uinput2))
print "%s \t\t\t%s \t(value.decode('utf8'))" % (uinput.decode("utf-8"), uinput2.decode("utf-8"))
print "%s \t\t\t%s \t(normalize('NFC',value))" % (normalize("NFC",uinput.decode("utf-8")), normalize("NFC",uinput2.decode("utf-8")));
print "\n\nUser Input \t\tProgram Input (Repr)"
print "-"*50
print "%s \t%s" % (repr(uinput),repr(uinput2))
print "%s \t%s \t(unicode(value))" % (repr(unicode(uinput)), repr(uinput2))
print "%s \t%s \t(value.decode('utf8'))" % (repr(uinput.decode("utf-8")), repr(uinput2.decode("utf-8")))
print "%s \t%s \t(normalize('NFC',value)))" % (repr(normalize("NFC",uinput.decode("utf-8"))), repr(normalize("NFC",uinput2.decode("utf-8"))));
打印:
type árbol: árbol
Encoding utf-8
User Input Program Input
--------------------------------------------------
árbol árbol (raw value)
árbol árbol (unicode(value))
árbol árbol (value.decode('utf8'))
árbol árbol (normalize('NFC',value))
User Input Program Input (Repr)
--------------------------------------------------
'\xc3\x83\xc2\xa1rbol' u'\xe1rbol'
u'\xc3\xa1rbol' u'\xe1rbol' (unicode(value))
u'\xc3\xa1rbol' u'\xe1rbol' (value.decode('utf8'))
u'\xc3\xa1rbol' u'\xe1rbol' (normalize('NFC',value)))
任何想法? 當我使用Java之類的其他語言時,我沒有問題。 這僅發生在python中。 我正在使用Eclipse。
提前致謝 :)
您能檢查一下終端的字符編碼嗎?
導入系統
sys.stdin.encoding
如果它是UTF-8,則解碼應該可以。 否則,您必須使用正確的編碼對raw_input進行解碼。
像raw_input()。decode(sys.stdin.encoding)一樣檢查它是否正確(如果需要)和Unicode Normalization。
您當前的方法還不錯,但是您可能應該使用unicodedata.normalize()
進行比較。 上面鏈接的文檔解釋了為什么這是一個好主意。 例如,嘗試評估以下內容:
u'Ç' == u'Ç'
劇透警報,這將為您提供False
因為左側是序列U + 0043(拉丁文大寫字母C)U + 0327(合並CEDILLA),右側是單個字符U + 00C7(拉丁文大寫字母C和CEDILLA) )。
您可以使用unicodedata.normalize()
正確處理此問題,方法是先將字符串轉換為規范化形式。 例如:
# -*- coding: utf-8 -*-
from unicodedata import normalize
from __future__ import unicode_literals
user_input = normalize('NFC', raw_input("Please, write árido: ").decode("utf8"))
if normalize('NFC', u"árido") == user_input:
print "OK"
else:
print "FALSE"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.