python调用自定义模块的时候出现decode错误

发布于 2022-09-06 21:33:13 字数 5129 浏览 16 评论 0

出现的问题:

  • python调用自定义模块的时候出现decode错误: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 18: ordinal not in range(128)
  • 但是在该模块下执行相关函数却没不会出现问题

相关模块代码:

  • 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

'''
传入一个csv文件,根据csv文件绘图
设置异常处理
'''
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")
    

编译器提示错误情况:

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)

如果单独运行drawing.py是没问题的,情况如下

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

在没有发到segmentfault上之前也百度过一些相关资料,都是说是与程序中出现中文有关,但是我的程序中也没有中文字符呀?所以现在很迷茫。实在是找不到问题所在了......希望前辈们能告知一下晚辈那里出错了,万分感谢!!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

被翻牌 2022-09-13 21:33:13

路径中有中文

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)
>>>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文