Skip to main content
 首页 » 编程设计

python之处理 Unicode 字符

2024年12月31日11lonelyxmas

我知道这个问题以前被问过无数次,但我似乎无法找到任何解决方案。我试过使用 codecs 模块,io 模块。似乎没有任何效果。

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

AHIMSA Centro de Sanación Pránica,能量疗愈

此外,我不确定 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)) 
... 

如有任何帮助,我们将不胜感激!

请您参考如下方法:

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

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])))