简体   繁体   English

将输出重定向到文件时出现UnicodeEncodeError-python 2.7

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

I have to redirect the output of a googlemaps API function to a file. 我必须将googlemaps API函数的输出重定向到文件。 I have a few objects in my pandas dataframe and I am getting their addresses through the google 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)

As I do so, I get the error: 当我这样做时,我得到了错误:

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

If I simply print it to the screen it works flawlessly and it displays a well formatted address; 如果我只是将其打印到屏幕上,它就可以正常工作,并且显示格式正确的地址; the issue is in the process of writing it to an external file. 问题出在将其写入外部文件的过程中。 I think I understand what the error message is telling me - there is some character in the output which is not encoded in utf8 - but I don't know how to work around it and have my output written to my csv. 我想我知道错误消息告诉我的内容-输出中有一些字符未以utf8编码-但是我不知道如何解决该问题并将输出写入到csv中。

Problem solved. 问题解决了。 Turns out the issue wasn't the result from the API but the row['object'] from the df. 原来问题不是来自API的结果,而是df的row['object'] I wrote a simple function 我写了一个简单的函数

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

and then I just edited the second for loop: 然后我刚刚编辑了第二个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