首页 文章

Python - UnicodeEncodeError - 使用gspread in print功能编码('utf-8')

提问于
浏览
0

我试图运行一个gspread代码,从谷歌电子表格打印信息 . 该工作表包含í,ú和ó字符 - 这是我得到的UnicodeEncodeError的原因 .

我读了Unicode HOWTO和其他所有来源都告诉你使用".encode('utf-8')"或decode(),但不知道如何在我的情况下与print函数一起实现它 .

我尝试过这样的事情:

#dsheet = sheet.encode('utf-8')

# -*- coding: utf-8 -*-

没有效果 .

我在MacOS上使用python 3 .

(代码工作我删除了所有的UTF字符手册 - 我只是想知道将来如何计算编码)

代码:

# -*- coding: utf-8 -*-
import gspread
from oauth2client.service_account import ServiceAccountCredentials


# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("Legislators 2017").sheet1

#dsheet = sheet.encode('utf-8')
# Extract and print all of the values
list_of_hashes = sheet.get_all_records()
print(list_of_hashes)

错误:

------
Traceback (most recent call last):
  File "spreadsheet.py", line 18, in <module>
    print(list_of_hashes)
UnicodeEncodeError: 'ascii' codec can't encode character '\xed' in position 84066: ordinal not in range(128)
------
Traceback (most recent call last):
  File "spreadsheet.py", line 18, in <module>
    print(list_of_hashes)
UnicodeEncodeError: 'ascii' codec can't encode character '\xf3' in position 398608: ordinal not in range(128)
-------
-------

1 回答

  • 1

    我修复了问题,发现它不是唯一的问题 . 我在Mac上将PYTHONIOENCODING设置为UTF-8:只需输入:

    export PYTHONIOENCODING=utf-8
    

    在标准终端窗口中 . 不是在Python Shell中!

    在这种特殊情况下,我使用了仍然显示错误的Atom-Runner . 要解决方法,您可以在系统代码中将编码指定为utf-8:

    import sys
    import io
    
    sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
    sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
    

    哪个做了伎俩 .

相关问题