【问题标题】:Convert data stored in latin1 to utf-8将存储在 latin1 中的数据转换为 utf-8
【发布时间】:2014-03-08 19:54:34
【问题描述】:

我想将一个 latin1 数据转换为 utf-8。

models.py

class old_product(models.Model):
    product_description = models.CharField(max_length=200)  # This field is latin1

class product(models.Model):
    name = models.CharField(max_length=200) # This field is utf-8

view.py

def index(request):
    old_products =  old_product.objects.all()
    for product in old_products:
            product_id = product.product_id
            names = product.product_description
            name =  names.decode('latin1').encode('utf-8')  
            c = product_name(id = product_id,name = name)
            c.save()
    return render_to_response('products/all_products.html',{},context_instance=RequestContext(request))            

在这里,我将所有以前的数据从old_product 表移动到另一个表product。首先,当我将数据存储在latin1 中的old_product 表中时,现在我想将其转换为utf-8 并希望存储在product 表中。这就是数据存储在old_product 表中的方式 - STONE حجر (ctn80pcs)

当我尝试这个name = names.decode('latin1') 和这个name = names.decode('latin1').encode('utf-8') 时, 我遇到了这个错误'ascii' codec can't encode characters in position 7-12: ordinal not in range(128)。我该如何转换?

【问题讨论】:

    标签: django python-2.7 mysql-python


    【解决方案1】:

    尝试这样做

    name = names.decode('iso-8859-1').encode('utf8')
    

    python 支持 iso-8859-1,相当于 latin-1

    这是我的尝试:

    >>> latin = 'fides'.encode('iso-8859-1')
    >>> latin
    'fides'
    >>> ucode = latin.decode('utf8')
    >>> ucode
    u'fides'
    

    【讨论】:

    • 感谢您的回答。但它显示相同的错误 'ascii' 编解码器无法对位置 7-12 中的字符进行编码:序数不在范围内(128)。@CrazyGeek
    • 我在我身边试过但没有收到任何错误,请参阅我的更新答案。
    • 但我再次收到一个错误 latin-1' 编解码器无法在位置 6 编码字符 u'\u2026':序数不在范围内(256)。当我尝试转换这个词“VASE”时مزريا (ctn24pcs)" @CrazyGeek
    • 当我运行 ""VASE مزريا (ctn24pcs)".decode('utf8')" 我得到这个输出 "u'VASE \xd9\u2026\xd8\xb2\xd8 \xb1\xd9\u0160\xd8\xa7 (ctn24pcs)'" 所以这是你想要的吗?
    • 我已经通过了这个stereoplex.com/blog/python-unicode-and-unicodedecodeerror,我相信它会对你有帮助。
    猜你喜欢
    • 2013-09-18
    • 2018-12-26
    • 2017-02-13
    • 1970-01-01
    • 2011-09-26
    • 2011-07-14
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多