2011-01-07 9 views
1

私はPythonには全く慣れていませんが、使用する必要のあるパッケージを見つけてテストしています。問題のPythonパッケージはpywurflです。Pythonでhttp User-agentのUnicode文字を扱う

単純なテキストファイルの列からユーザーエージェント(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文字列を持つ列です。私は、私は「UTF8」が「latin1の」で置き換えた場合

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: unexpected code byte 

のように見えるエラーを取得する私は、次のエラー

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

は、私はここで何も悪いことをしていましたか?パッケージがそうであるので、UnicodeでUA文字列を変換する必要があります。私は、特にPythonのUnicodeに精通していません。このエラーをどうすれば処理できますか?たとえば、このエラーを出しているUA文字列を見つけて、もっと情報に基づいた質問をすることができますか?

答えて

2

2つの別々の問題があるようです。

最初は、入力ファイルがutf-8であると仮定していることです。入力コーディングを問題のlatin-1アドレスに変更します。

2番目の問題は、stdoutがascii出力用に設定されているように見えるため、書き込みが失敗します。そのためにはthis questionが役に立ちます。