Я пытаюсь воспроизвести простейшие примеры из учебника по боке на 64-разрядной версии Windows. машина с Python 3.3.0.
Вот код полностью
import pandas as pd
import numpy as np
import matplotlib.pyplot as mpl
# NOTE need this import as output_file was not getting imported into the
# global namespace
import bokeh.plotting as bkp
from bokeh.plotting import *
# Skip the first point because it can be troublesome
theta = np.linspace(0, 8*np.pi, 10000)[1:]
# Compute the radial coordinates for some different spirals
lituus = theta**(-1/2) # lituus
golden = np.exp(0.306349*theta) # golden
arch = theta # Archimedean
fermat = theta**(1/2) # Fermat's
# Now compute the X and Y coordinates (polar mappers planned for Bokeh later)
golden_x = golden*np.cos(theta)
golden_y = golden*np.sin(theta)
lituus_x = lituus*np.cos(theta)
lituus_y = lituus*np.sin(theta)
arch_x = arch*np.cos(theta)
arch_y = arch*np.sin(theta)
fermat_x = fermat*np.cos(theta)
fermat_y = fermat*np.sin(theta)
# output to static HTML file
bkp.output_file("lines.html")
# Plot the Archimedean spiral using the `line` renderer. Note how we set the
# color, line thickness, title, and legend value.
line(arch_x, arch_y, color="red", line_width=2, title="Archimean", legend="Archimedean")
Это дает мне следующую ошибку:
Traceback (most recent call last):
File "F:\programming\python\python64\python33\lib\site-packages\IPython\core\interactiveshell.py", line 2732, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-00be3b4eba05>", line 1, in <module>
bkp.line(arch_x, arch_y, color="red", line_width=2, title="Archimean", legend="Archimedean")
File "F:\programming\python\python64\python33\lib\site-packages\bokeh\plotting.py", line 318, in wrapper
save()
File "F:\programming\python\python64\python33\lib\site-packages\bokeh\plotting.py", line 284, in save
f.write(html)
File "F:\programming\python\python64\python33\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 1831286-1831289: character maps to <undefined>
Я понимаю, что это как-то связано с кодировкой, которую Python использует для записи в выходной файл, но недостаточно знаю о настройке кодировки выходного файла или кодировки, которая используется Python для записи, чтобы исправить это. Помощь приветствуется.
Редактировать:
Я попытался реализовать совет, данный здесь, чтобы всегда передавать вывод stdout через потоковый генератор:
if sys.stdout.encoding != 'UTF-8':
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
if sys.stderr.encoding != 'UTF-8':
sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')
но часть интерфейса, похоже, изменилась, и нет переменной sys.stdout.encoding
.
Traceback (most recent call last):
File "F:\programming\python\python64\python33\lib\site-packages\IPython\core\interactiveshell.py", line 2732, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-e12310bc7a07>", line 1, in <module>
if sys.stdout.encoding != 'UTF-8':
File "F:\programming\python\python64\python33\lib\codecs.py", line 387, in __getattr__
return getattr(self.stream, name)
AttributeError: '_io.FileIO' object has no attribute 'encoding'
sys.stdout
, но если вы хотите заменить ее в Python 3, используйтеsys.stdout = io.TextIOWrapper(sys.stdout.detach(), 'utf-8', 'strict')
. - person Eryk Sun   schedule 06.06.2014bokeh.plotting.save
не устанавливает кодировку для файла . Он использует значение по умолчанию изlocale.getprefferedencoding
. Боюсь, чтобы использовать это, вам понадобится либо обезьяний патчbokeh.plotting
, либоlocale
(_bootlocale
в 3.4). - person Eryk Sun   schedule 06.06.2014getprefferedencoding
в каталоге боке, и, похоже, он не использовался. Можете ли вы указать мне строки кода, где я могу явно установить кодировку вывода? - person tchakravarty   schedule 06.06.2014open(filename, "w")
неявно используетgetprefferedencoding
, если вы не указали явныйencoding
, такой какopen(filename, "w", encoding="utf-8")
. - person Eryk Sun   schedule 06.06.2014encoding='utf-8'
? - person tchakravarty   schedule 06.06.2014output_file
. - person tchakravarty   schedule 06.06.2014getpreferredencoding
вызывает_locale._getdefaultlocale
, который вызывает Windows APIGetACP
. - person Eryk Sun   schedule 06.06.2014import ctypes; print(ctypes.windll.kernel32.GetACP())
. - person Eryk Sun   schedule 07.06.2014