python - 将微符号字符保存在 mongo 集合中

标签 python unicode python-unicode

我正在编写一个 python 脚本来创建基于 MySql 数据库的 mongo 集合。问题出在微符号字符上:

bson.errors.InvalidStringData: strings in documents must be valid UTF-8: '\xb5g'

我尝试使用不同的代码(utf-8、latin-1、cp1252、iso-8859-2)对值进行编码/解码,但没有成功,但总是收到以下错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in position 0: ordinal not in   range(128)

这是从 mysql 数据库获取数据的代码。数据库是USDA 0 :

    # -*- encoding: utf-8 -*-

    import MySQLdb
    mysqldb = MySQLdb.connect(DBCONF)
    cursor = mysqldb.cursor()
    foodid = 1001
    q = (
        ' SELECT nut.Nutr_Val,'
        ' nutdef.Units,'
        ' nutdef.NutrDesc, nutdef.Tagname'
        ' FROM food_des AS f'
        ' JOIN nutrient AS nut ON nut.NDB_No = f.NDB_No'
        ' JOIN nutrient_def AS nutdef ON nutdef.Nutr_No = nut.Nutr_No'
        ' WHERE f.NDB_No = %s'
    ) % str(foodid)
    self.cursor.execute(q)

带有微符号字符的字段是 nutdef.Units 1。

最佳答案

尝试将字符解码为 latin-1:

a = '\xb5g'
# '\xb5g'
print a
# ?g

b = a.decode('latin-1')
print b
# µg

b
# u'\xb5g'

或者您可以通过告诉 MySQL 连接在所有 CHAR、VARCHAR 和 TEXT 字段上使用 unicode 来修复此问题:

MySQLdb.connect(..., use_unicode=True)

关于python - 将微符号字符保存在 mongo 集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12014362/

相关文章:

python - 在 Python 中查找箭头键的值 : Why are they triples?

python - 使用 Python 从 Azure Monitor 获取特定警报

python - 使用字典而不是列表的开销是多少?

matlab - 将unicode字符串写入Matlab中的文件

python - 使用两个模型进行全文搜索

javascript - Jquery,检查 charAt() 是否等于 unicode 字符?

c - 如何开始使用 C 语言的 ICU

python - 如何允许打开文件名中包含 Unicode 字符的文件?

python - 在 python 中抓取页面时保留非拉丁字符

pytest - 在pypy下比较pytest中的unicode在第一次运行时失败