【发布时间】:2011-01-07 17:21:23
【问题描述】:
我对 python 完全陌生,但我找到了一个需要使用的包并正在对其进行测试。有问题的python包是pywurfl。
我创建了一个基于示例的简单代码,该示例通过从简单文本文件的列中读取用户代理 (UA) 字符串。有大量的 UA(有些可能有外来字符)。现在包含 UA 的文件已使用 bash 输出命令 ">" 和 perl 脚本生成。例如 perl somescript.pl > outfile.txt。
但是,在该文件中运行以下代码时出现错误。
#!/usr/bin/python
import fileinput
import sys
from wurfl import devices
from pywurfl.algorithms import LevenshteinDistance
for line in fileinput.input():
line = line.rstrip("\r\n") # equiv of chomp
H = line.split('\t')
if H[27]=='Mobile':
user_agent = H[23].decode('utf8')
search_algorithm = LevenshteinDistance()
device = devices.select_ua(user_agent, search=search_algorithm)
sys.stdout.write( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s" % (user_agent, device.devid, device.devua, device.fall_back, device.actual_device_root, device.brand_name, device.marketing_name, device.model_name, device.device_os, device.device_os_version, device.mobile_browser, device.mobile_browser_version, device.model_extra_info, device.pointing_method, device.has_qwerty_keyboard, device.is_tablet, device.has_cellular_radio, device.max_data_rate, device.wifi, device.dual_orientation, device.physical_screen_height, device.physical_screen_width,device.resolution_height, device.resolution_width, device.full_flash_support, device.built_in_camera, device.built_in_recorder, device.receiver, device.sender, device.can_assign_phone_number, device.is_wireless_device, device.sms_enabled) + "\n")
else:
# do something else
pass
这里的 H[23] 是具有 UA 字符串的列。但我收到一个看起来像
的错误UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: unexpected code byte
当我将 'utf8' 替换为 'latin1' 时,出现以下错误
sys.stdout.write(................) # with the .... as in the code
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa9' in position 0: ordinal not in range(128).
我在这里做错了吗?我需要将 UA 字符串转换为 Unicode,因为包是这样的。我不太精通Unicode,尤其是python。我将如何处理这个错误?例如,找出导致此错误的 UA 字符串,以便我可以提出更明智的问题?
【问题讨论】:
标签: python unicode error-handling user-agent