在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/Python/ python調(diào)用自定義模塊的時(shí)候出現(xiàn)decode錯(cuò)誤

python調(diào)用自定義模塊的時(shí)候出現(xiàn)decode錯(cuò)誤

出現(xiàn)的問(wèn)題:

  • python調(diào)用自定義模塊的時(shí)候出現(xiàn)decode錯(cuò)誤: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 18: ordinal not in range(128)
  • 但是在該模塊下執(zhí)行相關(guān)函數(shù)卻沒(méi)不會(huì)出現(xiàn)問(wèn)題

相關(guān)模塊代碼:

  • data.csv文件
Word,Count
nation,5
dedicated,4
people,3
dead,3
living,2
devotion,2
dedicate,2
conceived,2
vain,1
unfinished,1
testing,1
task,1
struggled,1
sense,1
score,1
resolve,1
remember,1
remaining,1
proposition,1
proper,1
power,1
portion,1
perish,1
nobly,1
measure,1
lives,1
live,1
liberty,1
larger,1
increased,1
honored,1
highly,1
hallow,1
ground,1
government,1
god,1
freedom,1
fought,1
forget,1
fitting,1
final,1
field,1
fathers,1
equal,1
engaged,1
endure,1
earth,1
died,1
detract,1
created,1
continent,1
consecrated,1
consecrate,1
civil,1
brought,1
brave,1
birth,1
battle-field,1
altogether,1
ago,1
advanced,1
  • drawing.py文件
#!/usr/bin/env python
# coding=utf-8

'''
傳入一個(gè)csv文件,根據(jù)csv文件繪圖
設(shè)置異常處理
'''
import pandas as pd

class DrawingDict:
    def __init__(self, csv_path):
        try:
            self.csv_file = pd.read_csv(csv_path)
        except Exception as err:
            print "drawung.py : %s" % err
     
    def __proc_csv(self, key, ascdStat=False, endInd=10):
        self.get_info = self.csv_file.sort_values(key, ascending=False)[:endInd]
    
    def drawing(self, key, ascdStat=False, endInd=10):
        self.__proc_csv(key, ascdStat, endInd)
        print "self.get_info is : \n%s\n" % (self.get_info)
        
        print type(self.get_info)

        print "%s" % self.get_info["Word"]
        try:
            data_plot = self.get_info.plot(kind="bar", x=self.get_info["Word"], title="Words Count Table", legend=False)
        except Exception as err:
            print err
        fig = data_plot.get_figure()
        fig.savefig("../DataAnalysisTraining/img.png")

if __name__ == '__main__':
    dd = DrawingDict("./data.csv")
    dd.drawing("Count")
  • main.py 代碼
#!/usr/bin/env python
# coding=utf-8

from drawing import DrawingDict 
from word_statistic import wordStatistic

if __name__ == "__main__":
    # st = wordStatistic("./Gettysburg_Address.txt");
    # print st.Statistic()
    # st.prettyPrint() 
    # st.save_csv("./data.csv")
    dd = DrawingDict("./data.csv")
    dd.drawing("Count")
    

編譯器提示錯(cuò)誤情況:

zgx@zgx:~/文檔/GitHub/DataAnalysisTraining$ python main.py 
self.get_info is : 
        Word  Count
0     nation      5
1  dedicated      4
2     people      3

<class 'pandas.core.frame.DataFrame'>
0       nation
1    dedicated
2       people
Name: Word, dtype: object
Traceback (most recent call last):
  File "main.py", line 13, in <module>
    dd.drawing("Count")
  File "/home/zgx/文檔/GitHub/DataAnalysisTraining/drawing.py", line 33, in drawing
    data_plot = self.get_info.plot(kind="bar", x=self.get_info["Word"], title="Words Count Table", legend=False)
  File "/home/zgx/anaconda2/lib/python2.7/site-packages/pandas/plotting/_core.py", line 2677, in __call__
    sort_columns=sort_columns, **kwds)
  File "/home/zgx/anaconda2/lib/python2.7/site-packages/pandas/plotting/_core.py", line 1902, in plot_frame
    **kwds)
  File "/home/zgx/anaconda2/lib/python2.7/site-packages/pandas/plotting/_core.py", line 1727, in _plot
    plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
  File "/home/zgx/anaconda2/lib/python2.7/site-packages/pandas/plotting/_core.py", line 1174, in __init__
    MPLPlot.__init__(self, data, **kwargs)
  File "/home/zgx/anaconda2/lib/python2.7/site-packages/pandas/plotting/_core.py", line 143, in __init__
    grid = False if secondary_y else self.plt.rcParams['axes.grid']
  File "pandas/_libs/properties.pyx", line 38, in pandas._libs.properties.cache_readonly.__get__
  File "/home/zgx/anaconda2/lib/python2.7/site-packages/pandas/plotting/_core.py", line 542, in plt
    import matplotlib.pyplot as plt
  File "/home/zgx/.local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 71, in <module>
    from matplotlib.backends import pylab_setup
  File "/home/zgx/.local/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 16, in <module>
    line for line in traceback.format_stack()
  File "/home/zgx/.local/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 18, in <genexpr>
    if not line.startswith('  File "<frozen importlib._bootstrap'))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 18: ordinal not in range(128)

如果單獨(dú)運(yùn)行drawing.py是沒(méi)問(wèn)題的,情況如下

zgx@zgx:~/文檔/GitHub/DataAnalysisTraining$ python drawing.py
self.get_info is : 
        Word  Count
0     nation      5
1  dedicated      4
2     people      3

<class 'pandas.core.frame.DataFrame'>
0       nation
1    dedicated
2       people
Name: Word, dtype: object

在沒(méi)有發(fā)到segmentfault上之前也百度過(guò)一些相關(guān)資料,都是說(shuō)是與程序中出現(xiàn)中文有關(guān),但是我的程序中也沒(méi)有中文字符呀?所以現(xiàn)在很迷茫。實(shí)在是找不到問(wèn)題所在了......希望前輩們能告知一下晚輩那里出錯(cuò)了,萬(wàn)分感謝!??!

回答
編輯回答
不二心

路徑中有中文

a = '文檔'
a.encode('utf-8') # b'\xe6\x96\x87\xe6\xa1\xa3'

>>> a.encode('utf-8').decode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
>>>
2017年10月5日 13:26