首页 > 解决方案 > 处理 Unicode 字符

问题描述

我知道这个问题之前已经被问过无数次,但我似乎无法让任何解决方案发挥作用。我试过使用codecs模块,io模块。似乎没有任何效果。

我正在从网上抓取一些东西,然后将每个项目的详细信息记录到一个文本文件中,但是脚本一旦遇到 Unicode 字符就会中断。

AHIMSA Centro de Sanación Pránica, Pranic Healing

此外,我不确定 Unicode 字符可能会在何时何地弹出,这增加了额外的复杂性,因此我需要一个总体解决方案,但我不确定如何处理潜在的非 ASCII 字符。

我不确定是否会在生产环境中使用 Python 3.6.5,因此该解决方案必须与 2.7 一起使用。

我可以在这里做什么?我该如何处理?

# -*- coding: utf-8 -*-
...
with open('test.txt', 'w') as f:
f.write(str(len(discoverable_cards)) + '\n\n')
    for cnt in range(0, len(discoverable_cards)):
        t = get_time()
        f.write('[ {} ] {}\n'.format(t, discoverable_cards[cnt]))
        f.write('[ {} ] {}\n'.format(t, cnt + 1))
        f.write('[ {} ] {}\n'.format(t, product_type[cnt].text))
        f.write('[ {} ] {}\n'.format(t, titles[cnt].text))
...

任何帮助,将不胜感激!

标签: pythonpython-2.7unicodecharacter-encoding

解决方案


鉴于您在 python2.7 中,您可能希望在将所有字符串传递给 Unicode 兼容字符集(如“utf8”)之前对其进行显式编码write,您可以使用简单的编码方法来做到这一点:

def safe_encode(str_or_unicode):
    # future py3 compatibility: define unicode, if needed:
    try:
       unicode
    except NameError:
       unicode = str
    if isinstance(str_or_unicode, unicode):
        return str_or_unicode.encode("utf8")
    return str_or_unicode

然后你会像这样使用它:

f.write('[ {} ] {}\n'.format(safe_encode(t), safe_encode(discoverable_cards[cnt])))

推荐阅读