python matplotlib阶段性总结——word转txt、绘图、文件操作
生活随笔
收集整理的這篇文章主要介紹了
python matplotlib阶段性总结——word转txt、绘图、文件操作
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
代碼說話:
# -*- coding: cp936 -*-import os import re import sys import chardet import fnmatch import win32com.client import numpy as np import matplotlib.pyplot as plt #顯示中文包 from matplotlib.font_manager import FontProperties#獲取絕對路徑PATH = os.path.abspath(os.path.dirname(sys.argv[0]))""" 使用到的變量 """first_f = 0 first_month = 0 first_year = 0 file_cnt = 0 all_money = 0 #week_money = [0] week_money = [1342.8, 401.2, 158.0, 250.0, 870.0,117.2, 860.4, 240.8, 283.3, 488.8,442.5, 331.4, 337.12, 742.7, 638.2,430.0, 253.2, 130.3, 614.5, 450.1,198.8, 221.2, 324.9, 979.02, 170.8,204.0, 560.3, 1106.3, 126.3, 639.6,832.7, 631.0, 888.5, 952.7, 475.8,751.0, 130.0, 459.1, 190.5, 1127.3,308.5, 152.5, 844.0, 1394.4, 319.8,1172.3, 789.51, 1277.3, 277.2, 742.3,467.6, 580.7, 1263.4, 570.9, 381.5,670.7, 607.5, 1219.0, 381.2, 398.0,1132.5, 234.21, 701.4, 1160.1, 460.6,353.4, 375.3, 137.0, 100.4, 724.2,422.8, 684.4, 605.4, 679.3, 120.5,159.5, 915.5, 965.5, 346.5, 254.5,466.0, 1171.2, 190.0, 1075.7, 234.8,198.79, 762.74, 332.57, 224.5, 207.0,963.8, 750.44, 188.0, 624.1, 331.5,473.1, 164.8, 207.5, 187.5, 135.5]new_month = [0] month_money = [0] basic_month = [u'2月',u'3月',u'4月',u'5月',u'6月',u'7月',u'8月',u'9月',u'10月',u'11月',u'12月']""" 繪制花費曲線 """ def money_plot():#使用windows系統(tǒng)自帶字體font = FontProperties(fname=r"C:\\WINDOWS\\Fonts\\simsun.ttc", size=10)#設(shè)置圖表1尺寸plt.figure(figsize=(13,9.5))global week_moneyglobal month_moneyglobal new_monthx1 = range(0,len(week_money))y1 = week_money#x2使用條件表達式,不能被4整除時長度要+1x2 = range(0,len(week_money)%4==0 and len(week_money)/4 or len(week_money)/4+1)y2 = month_moneyplt.subplot(211)plt.plot(x1,y1,'r',label="money")plt.plot(x1,y1,'bo')plt.title(u"每周花費統(tǒng)計",fontproperties=font)plt.xlabel(u"周數(shù)",fontproperties=font)plt.ylabel(u"金額(¥)",fontproperties=font)plt.grid(True,color='g',linewidth=1)plt.legend()plt.subplot(212)plt.plot(x2, y2,'c',label="money")plt.plot(x2, y2,'bo')plt.xticks(x2,new_month,rotation=40,fontproperties=font)plt.title(u"每月花費統(tǒng)計",fontproperties=font)plt.xlabel(u"月份",fontproperties=font)plt.ylabel(u"金額(¥)",fontproperties=font)plt.grid(True,color='g',linewidth=1)plt.legend()plt.savefig("figure.png",format="png")plt.show()""" 將每周的花費轉(zhuǎn)化為每月的花費 """new_month = [0]def week_to_month():#聲明使用的全局變量global week_moneyglobal month_moneyglobal first_monthglobal first_yearglobal new_monthglobal basic_month#將每周的花費轉(zhuǎn)換為每月的花費sum = 0for i in range(0,len(week_money)):sum += week_money[i]#每4周計算一次月消費if i%4 == 3:if month_money[0] == 0:month_money[0] = round(sum,2)else:month_money.append(round(sum,2))sum = 0#不足一月按一月算if i == len(week_money)-1:if len(week_money)%4 != 0:month_money.append(round(sum,2))sum = 0#print "\n\n",month_money,"\n","total len_month",len(month_money)#計算月份編號表index = first_monthwhile index < len(month_money)+first_month:if new_month[0] == 0:if index == 1:new_month[0] = str(first_year)else:new_month[0] = basic_month[index-2]#偏移為2,固減去2elif index%12 == 0:new_month.append(basic_month[12-2])elif index%12 == 1:new_month.append(str(first_year+index/12))else: new_month.append(basic_month[index%12-2])index += 1#for i in range(len(new_month)):#print new_month[i].encode('utf8')""" 提取文件中每周的花費并保存下來 """def read_txt_data():#讀取txt文件內(nèi)容global week_moneyglobal all_moneyglobal file_cntglobal first_fglobal first_monthglobal first_yeartmp_money = 0for root, dirs,files in os.walk(PATH):for _dir in dirs:passfor _file in files:if fnmatch.fnmatch(_file,'*.txt'):work_file = os.path.join(root, _file)f = open(work_file,'r')line = f.readline()print line#輸出第一行的日期if first_f == 0: #執(zhí)行一次:讀取第一次的年份和月份,后面依次累加first_f = 1date_data = re.findall(r"\d+\.?\d*",line)first_year = int(date_data[0])/10000first_month = int(date_data[0])%10000/100#print "year",first_year ,"month",first_monthelse:passwhile True:line = f.readline()if line:#打印每一行的內(nèi)容#print line,content = linestart = content.find("總計")#注意讀出來的文本編碼方式#判斷是否是"總計那一行"if start != -1:#print start#獲取位置num = re.findall(r"\d+\.?\d*",content)tmp_money = round(float(num[0]),2)#輸出其中的數(shù)字if week_money[0] == 0:week_money[0] = tmp_moneyelse:week_money.append(tmp_money)file_cnt += 1print "Your week money is",tmp_moneyall_money = all_money + tmp_moneyelse:passelse:breakf.close()print "\n","All used money is",all_moneyelse:continueprint "\n","eve_week_money:",week_money,"\n","total file:",file_cnt""" 將word文檔轉(zhuǎn)化為txt文檔 """ def word_to_txt():file_cnt = 0wordapp = win32com.client.gencache.EnsureDispatch("Word.Application")#輸出路徑print "Current path is "+PATH #異常處理try:#遍歷文件for root, dirs,files in os.walk(PATH):for _dir in dirs:passfor _file in files:#匹配doc文件if not fnmatch.fnmatch(_file,'*.doc'):#跳出循環(huán)語句continue#將目錄和文件名拼接 例如:c:\smart\test.docword_file = os.path.join(root, _file)wordapp.Documents.Open(word_file)#修改成txt文件名 word_file[:-3]表示取從開始到倒數(shù)第三個字符docastxt = word_file[:-3] +'txt'#轉(zhuǎn)換成txt文件wordapp.ActiveDocument.SaveAs(docastxt,FileFormat = win32com.client.constants.wdFormatText)wordapp.ActiveDocument.Close()file_cnt += 1print "file %dth convert success ."%file_cntfinally:wordapp.Quit()print "All file convert success !"if __name__ == '__main__':try:#word_to_txt()read_txt_data()week_to_month()money_plot()except IOError, e:print e 繪圖如下:
分析后續(xù)加上。。。。。
總結(jié)
以上是生活随笔為你收集整理的python matplotlib阶段性总结——word转txt、绘图、文件操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js读取json文件(原生和jQuery
- 下一篇: 索引常用注意事项