python matplotlib阶段性总结——word转txt、绘图、文件操作

来源:互联网 发布:olay新生塑颜系列知乎 编辑:程序博客网 时间:2024/06/17 22:31

源自:http://blog.csdn.net/fortware/article/details/51935103

[python] view plain copy
 print?
  1. # -*- coding: cp936 -*-  
  2.   
  3. import os  
  4. import re  
  5. import sys  
  6. import chardet  
  7. import fnmatch  
  8. import win32com.client  
  9. import numpy as np  
  10. import matplotlib.pyplot as plt  
  11. #显示中文包  
  12. from matplotlib.font_manager import FontProperties  
  13.   
  14. #获取绝对路径  
  15.   
  16. PATH = os.path.abspath(os.path.dirname(sys.argv[0]))  
  17.   
  18. """ 
  19. 使用到的变量 
  20. """  
  21.   
  22. first_f = 0  
  23. first_month = 0  
  24. first_year = 0  
  25. file_cnt = 0  
  26. all_money = 0  
  27. #week_money = [0]  
  28. week_money = [1342.8401.2158.0250.0870.0,  
  29.      117.2860.4240.8283.3488.8,  
  30.      442.5331.4337.12742.7638.2,  
  31.      430.0253.2130.3614.5450.1,  
  32.      198.8221.2324.9979.02170.8,  
  33.      204.0560.31106.3126.3639.6,  
  34.      832.7631.0888.5952.7475.8,  
  35.      751.0130.0459.1190.51127.3,  
  36.      308.5152.5844.01394.4319.8,  
  37.      1172.3789.511277.3277.2742.3,  
  38.      467.6580.71263.4570.9381.5,  
  39.      670.7607.51219.0381.2398.0,  
  40.      1132.5234.21701.41160.1460.6,  
  41.      353.4375.3137.0100.4724.2,  
  42.      422.8684.4605.4679.3120.5,  
  43.      159.5915.5965.5346.5254.5,  
  44.      466.01171.2190.01075.7234.8,  
  45.      198.79762.74332.57224.5207.0,  
  46.      963.8750.44188.0624.1331.5,  
  47.      473.1164.8207.5187.5135.5]  
  48.   
  49. new_month = [0]  
  50. month_money = [0]  
  51. basic_month = [u'2月',u'3月',u'4月',u'5月',  
  52.                u'6月',u'7月',u'8月',u'9月',  
  53.                u'10月',u'11月',u'12月']  
  54.   
  55. """ 
  56. 绘制花费曲线 
  57. """  
  58. def money_plot():  
  59.     #使用windows系统自带字体  
  60.     font = FontProperties(fname=r"C:\\WINDOWS\\Fonts\\simsun.ttc", size=10)  
  61.     #设置图表1尺寸  
  62.     plt.figure(figsize=(13,9.5))  
  63.     global week_money  
  64.     global month_money  
  65.     global new_month  
  66.     x1 = range(0,len(week_money))  
  67.     y1 = week_money  
  68.     #x2使用条件表达式,不能被4整除时长度要+1  
  69.     x2 = range(0,len(week_money)%4==0 and len(week_money)/4 or len(week_money)/4+1)  
  70.     y2 = month_money  
  71.       
  72.     plt.subplot(211)  
  73.     plt.plot(x1,y1,'r',label="money")  
  74.     plt.plot(x1,y1,'bo')  
  75.       
  76.     plt.title(u"每周花费统计",fontproperties=font)  
  77.     plt.xlabel(u"周数",fontproperties=font)  
  78.     plt.ylabel(u"金额(¥)",fontproperties=font)  
  79.     plt.grid(True,color='g',linewidth=1)  
  80.     plt.legend()  
  81.   
  82.     plt.subplot(212)  
  83.     plt.plot(x2, y2,'c',label="money")  
  84.     plt.plot(x2, y2,'bo')  
  85.       
  86.     plt.xticks(x2,new_month,rotation=40,fontproperties=font)  
  87.       
  88.     plt.title(u"每月花费统计",fontproperties=font)  
  89.     plt.xlabel(u"月份",fontproperties=font)  
  90.     plt.ylabel(u"金额(¥)",fontproperties=font)  
  91.     plt.grid(True,color='g',linewidth=1)  
  92.     plt.legend()  
  93.     plt.savefig("figure.png",format="png")  
  94.     plt.show()  
  95.   
  96.   
  97. """ 
  98. 将每周的花费转化为每月的花费 
  99. """  
  100.   
  101. new_month = [0]  
  102.   
  103.   
  104. def week_to_month():  
  105.     #声明使用的全局变量  
  106.     global week_money  
  107.     global month_money  
  108.     global first_month  
  109.     global first_year  
  110.     global new_month  
  111.     global basic_month  
  112.     #将每周的花费转换为每月的花费  
  113.     sum = 0  
  114.     for i in range(0,len(week_money)):  
  115.         sum += week_money[i]  
  116.         #每4周计算一次月消费  
  117.         if i%4 == 3:  
  118.             if month_money[0] == 0:  
  119.                 month_money[0] = round(sum,2)  
  120.             else:  
  121.                 month_money.append(round(sum,2))  
  122.             sum = 0  
  123.         #不足一月按一月算  
  124.         if i == len(week_money)-1:  
  125.             if len(week_money)%4 != 0:  
  126.                 month_money.append(round(sum,2))  
  127.                 sum = 0  
  128.     #print "\n\n",month_money,"\n","total len_month",len(month_money)  
  129.   
  130.     #计算月份编号表  
  131.       
  132.     index = first_month  
  133.     while index < len(month_money)+first_month:  
  134.         if new_month[0] == 0:  
  135.             if index == 1:  
  136.                 new_month[0] = str(first_year)  
  137.             else:  
  138.                 new_month[0] = basic_month[index-2]#偏移为2,固减去2  
  139.         elif index%12 == 0:  
  140.             new_month.append(basic_month[12-2])  
  141.         elif index%12 == 1:  
  142.             new_month.append(str(first_year+index/12))  
  143.         else:                  
  144.             new_month.append(basic_month[index%12-2])  
  145.         index += 1  
  146.     #for i in range(len(new_month)):  
  147.         #print new_month[i].encode('utf8')  
  148.           
  149. """ 
  150. 提取文件中每周的花费并保存下来 
  151. """  
  152.   
  153. def read_txt_data():  
  154.     #读取txt文件内容  
  155.     global week_money  
  156.     global all_money  
  157.     global file_cnt  
  158.     global first_f  
  159.     global first_month  
  160.     global first_year  
  161.       
  162.     tmp_money = 0  
  163.     for root, dirs,files in os.walk(PATH):  
  164.         for _dir in dirs:  
  165.             pass  
  166.         for _file in files:  
  167.             if fnmatch.fnmatch(_file,'*.txt'):  
  168.                 work_file = os.path.join(root, _file)  
  169.                 f = open(work_file,'r')  
  170.                 line = f.readline()  
  171.                   
  172.                 print line#输出第一行的日期  
  173.   
  174.                 if first_f == 0#执行一次:读取第一次的年份和月份,后面依次累加  
  175.                     first_f = 1  
  176.                     date_data = re.findall(r"\d+\.?\d*",line)  
  177.                     first_year = int(date_data[0])/10000  
  178.                     first_month = int(date_data[0])%10000/100  
  179.                     #print "year",first_year ,"month",first_month  
  180.                 else:  
  181.                     pass  
  182.                 while True:  
  183.                     line = f.readline()  
  184.                     if line:  
  185.                         #打印每一行的内容  
  186.                         #print line,  
  187.                         content = line  
  188.                         start = content.find("总计")#注意读出来的文本编码方式  
  189.                         #判断是否是"总计那一行"  
  190.                         if start != -1:  
  191.                             #print start  
  192.                             #获取位置  
  193.                             num = re.findall(r"\d+\.?\d*",content)  
  194.                             tmp_money = round(float(num[0]),2)  
  195.                             #输出其中的数字  
  196.                             if week_money[0] == 0:  
  197.                                 week_money[0] = tmp_money  
  198.                             else:  
  199.                                 week_money.append(tmp_money)  
  200.                             file_cnt += 1  
  201.                             print "Your week money is",tmp_money  
  202.                             all_money = all_money + tmp_money  
  203.                         else:  
  204.                             pass  
  205.                     else:  
  206.                         break  
  207.                 f.close()  
  208.                 print "\n","All used money is",all_money  
  209.             else:  
  210.                 continue  
  211.     print "\n","eve_week_money:",week_money,"\n","total file:",file_cnt  
  212.   
  213.   
  214. """ 
  215. 将word文档转化为txt文档 
  216. """  
  217. def word_to_txt():  
  218.     file_cnt = 0  
  219.     wordapp = win32com.client.gencache.EnsureDispatch("Word.Application")  
  220.     #输出路径  
  221.     print "Current path is "+PATH    
  222.     #异常处理  
  223.     try:  
  224.     #遍历文件  
  225.         for root, dirs,files in os.walk(PATH):  
  226.             for _dir in dirs:  
  227.                 pass  
  228.             for _file in files:  
  229.                 #匹配doc文件  
  230.                 if not fnmatch.fnmatch(_file,'*.doc'):  
  231.                     #跳出循环语句  
  232.                     continue  
  233.                 #将目录和文件名拼接 例如:c:\smart\test.doc  
  234.                 word_file = os.path.join(root, _file)  
  235.                 wordapp.Documents.Open(word_file)  
  236.         #修改成txt文件名  word_file[:-3]表示取从开始到倒数第三个字符  
  237.                 docastxt = word_file[:-3] +'txt'  
  238.                 #转换成txt文件  
  239.                 wordapp.ActiveDocument.SaveAs(docastxt,FileFormat = win32com.client.constants.wdFormatText)  
  240.                 wordapp.ActiveDocument.Close()  
  241.   
  242.                 file_cnt += 1  
  243.                 print "file %dth convert success ."%file_cnt  
  244.     finally:  
  245.         wordapp.Quit()  
  246.     print "All file convert success !"  
  247.   
  248.   
  249. if __name__ == '__main__':  
  250.     try:  
  251.         #word_to_txt()  
  252.         read_txt_data()  
  253.         week_to_month()  
  254.         money_plot()  
  255.     except IOError, e:  
  256.         print e  
  257.     

绘图如下:

消费


原创粉丝点击