次のよう__repr__()
にオブジェクトの関数を呼び出します。x
val = x.__repr__()
val
次に、文字列をSQLite
データベースに保存します。問題はそれval
がユニコードであるべきだということです。
私はこれを試しましたが成功しませんでした:
val = x.__repr__().encode("utf-8")
と
val = unicode(x.__repr__())
これを修正する方法を知っていますか?
使っていますPython 2.7.2
オブジェクトの表現はUnicodeであってはなりません。__unicode__
メソッドを定義し、オブジェクトをに渡しますunicode()
。
repr(x).decode("utf-8")
動作するunicode(repr(x), "utf-8")
はずです。
reprを使用してリストからテキストを引き出していたため、同様の問題が発生していました。
b =['text\xe2\x84\xa2', 'text2'] ## \xe2\x84\xa2 is the TM symbol
a = repr(b[0])
c = unicode(a, "utf-8")
print c
>>>
'text\xe2\x84\xa2'
私はついに参加して、代わりにテキストをリストから削除しようとしました
b =['text\xe2\x84\xa2', 'text2'] ## \xe2\x84\xa2 is the TM symbol
a = ''.join(b[0])
c = unicode(a, "utf-8")
print c
>>>
text™
今それは動作します!!!!
私はいくつかの異なる方法を試しました。unicode関数でreprを使用するたびに、機能しませんでした。以下の変数eのように、joinを使用するか、テキストを宣言する必要があります。
b =['text\xe2\x84\xa2', 'text2'] ## \xe2\x84\xa2 is the TM symbol
a = ''.join(b[0])
c = unicode(repr(a), "utf-8")
d = repr(a).decode("utf-8")
e = "text\xe2\x84\xa2"
f = unicode(e, "utf-8")
g = unicode(repr(e), "utf-8")
h = repr(e).decode("utf-8")
i = unicode(a, "utf-8")
j = unicode(''.join(e), "utf-8")
print c
print d
print e
print f
print g
print h
print i
print j
*** Remote Interpreter Reinitialized ***
>>>
'text\xe2\x84\xa2'
'text\xe2\x84\xa2'
textâ„¢
text™
'text\xe2\x84\xa2'
'text\xe2\x84\xa2'
text™
text™
>>>
お役に立てれば。
Python2では、次の2つのメソッドを定義できます。
#!/usr/bin/env python
# coding: utf-8
class Person(object):
def __init__(self, name):
self.name = name
def __unicode__(self):
return u"Person info <name={0}>".format(self.name)
def __repr__(self):
return self.__unicode__().encode('utf-8')
if __name__ == '__main__':
A = Person(u"皮特")
print A
Python3では、定義__repr__
するだけで問題ありません。
#!/usr/bin/env python
# coding: utf-8
class Person(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return u"Person info <name={0}>".format(self.name)
if __name__ == '__main__':
A = Person(u"皮特")
print(A)