python - 处理 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))
...
任何帮助,将不胜感激!
解决方案
鉴于您在 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])))
推荐阅读
- java - 无法访问视图以更改背景颜色
- php - PHP key() 返回数组中下一项的键,而不是当前项
- android - 为 dev staging 生产组织 android + firebase 项目 + 云功能
- .net - 使用 OWIN Auth 的 Web API 返回“此请求的授权已被拒绝”。使用 [Authorize] 执行每个操作
- python - 合并时间重叠的行 - Pandas
- c - Is it legal to access struct members via offset pointers from other struct members?
- python - Docker Scrapy 蜘蛛将数据保存到 Postgres 端口错误
- javascript - Webpack - 资产大小限制中的警告:以下资产超出建议的大小限制 (244 KiB)
- python-3.x - Pygame屏幕没有更新
- pandas - 如何通过检查列的数据重命名熊猫数据框列名