簡體   English   中英

將輸出重定向到文件時出現UnicodeEncodeError-python 2.7

[英]UnicodeEncodeError while redirecting output to file - python 2.7

我必須將googlemaps API函數的輸出重定向到文件。 我的熊貓數據框中有一些objects ,我正在通過Google API獲取它們的地址。

import googlemaps
from __future__ import print_function
f=open('output.csv', 'w')
for idx, row in df.iterrows():
    gmaps = googlemaps.Client(key="my_key")
    reverse_result = gmaps.reverse_geocode((row['lat'], row['lon']), result_type='administrative_area_level_3')
    for result in reverse_result:
        print (row['object'],result["formatted_address"], file=f)

當我這樣做時,我得到了錯誤:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 15: ordinal not in range(128)

如果我只是將其打印到屏幕上,它就可以正常工作,並且顯示格式正確的地址; 問題出在將其寫入外部文件的過程中。 我想我知道錯誤消息告訴我的內容-輸出中有一些字符未以utf8編碼-但是我不知道如何解決該問題並將輸出寫入到csv中。

問題解決了。 原來問題不是來自API的結果,而是df的row['object'] 我寫了一個簡單的函數

def force_to_unicode(text):
    return text if isinstance(text, unicode) else text.decode('utf8')

然后我剛剛編輯了第二個for循環:

for result in reverse_result:
        a=force_to_unicode(row['object']) 
        b=result['formatted_address']
        print(a,',',b, file=f) #write result to csv file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM