【问题标题】:Handling unicode characters of http User-agents in python在python中处理http用户代理的unicode字符
【发布时间】: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


    【解决方案1】:

    看起来你有两个不同的问题。

    首先,您假设输入文件是 utf-8,但实际上不是。将输入编码更改为 latin-1 可以解决该问题。

    第二个问题是您的标准输出似乎设置为 ascii 输出,因此写入失败。为此,this question 可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-09-04
      • 2010-11-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 2018-12-05
      • 1970-01-01
      • 2014-12-05
      • 2010-12-11
      相关资源
      最近更新 更多