1

ユーザーが入力した文字列を別の文字列と比較する最良の方法は何ですか?

例えば:

# -*- 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でのみ発生します。私はエクリプスを使用しています。

前もって感謝します :)

4

2 に答える 2

1

お使いの端末の文字コードを確認していただけないでしょうか。

システムをインポート

sys.stdin.encoding

UTF-8 の場合、デコードは問題ないはずです。それ以外の場合は、正しいエンコーディングで raw_input をデコードする必要があります。

raw_input().decode(sys.stdin.encoding) のように、必要に応じて Unicode 正規化とともに適切かどうかを確認します。

于 2013-07-17T17:51:18.517 に答える
0

現在のアプローチは悪くありませんが、おそらくunicodedata.normalize()比較に使用する必要があります。上記のリンクのドキュメントでは、これが良いアイデアである理由を説明しています。たとえば、以下を評価してみてください。

u'Ç' == u'Ç'

ネタバレ注意ですFalse。左側は一連の U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA) であり、右側は単一文字 U+00C7 (LATIN CAPITAL LETTER C WITH 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"
于 2013-07-17T17:41:58.253 に答える