我們有一個寫滿數(shù)據(jù)的txt文件,如何將它錄入Excel表格呢?
Python將txt文件錄入Excel
調(diào)用python中專門用于處理Excel表格的函數(shù)庫 xlwt,建議大家打開CMD輸入
pip3 install xlwt
檢查一下是否安裝了這個函數(shù)庫。沒安裝的會自動安裝。
建一個python文件,庫調(diào)用,主函數(shù),自定義函數(shù)都先寫好
import xlwt def writeinexcel(): if __name__ == "__main__": writeinexcel()
打開.txt文件
import xlwt def writeinexcel(): f = open('bZhanRank.txt','r',encoding='utf-8') #打開數(shù)據(jù)文本文檔,注意編碼格式的影響 if __name__ == "__main__": writeinexcel()
新建一個Excel表格
import xlwt def writeinexcel(): f = open('bZhanRank.txt','r',encoding='utf-8') #打開數(shù)據(jù)文本文檔,注意編碼格式的影響 wb = xlwt.Workbook(encoding = 'utf-8') #新建一個excel文件 ws1 = wb.add_sheet('first') #添加一個新表,名字為first if __name__ == "__main__": writeinexcel()
進行一下預處理,用上write函數(shù)
import xlwt def writeinexcel(): f = open('bZhanRank.txt','r',encoding='utf-8') #打開數(shù)據(jù)文本文檔,注意編碼格式的影響 wb = xlwt.Workbook(encoding = 'utf-8') #新建一個excel文件 ws1 = wb.add_sheet('first') #添加一個新表,名字為first ws1.write(0,0,'名稱') ws1.write(0,1,'播放數(shù)') ws1.write(0,2,'追番人數(shù) ') ws1.write(0,3,' 彈幕數(shù)') ws1.write(0,4,'點贊數(shù)量') ws1.write(0,5,'投幣數(shù)') row = 1 #寫入的起始行 col = 0 #寫入的起始列 wb.save("數(shù)據(jù)表.xls") if __name__ == "__main__": writeinexcel()
預處理效果如下
從文件讀取數(shù)據(jù)(以行為單位),并寫入Excel表格。不用擔心,我這里的一行數(shù)據(jù)里用 逗號(也可根據(jù)空格或其他符號)分割數(shù)據(jù),讓它們能存到對應列里。
import xlwt def writeinexcel(): f = open('bZhanRank.txt','r',encoding='utf-8') #打開數(shù)據(jù)文本文檔,注意編碼格式的影響 wb = xlwt.Workbook(encoding = 'utf-8') #新建一個excel文件 ws1 = wb.add_sheet('first') #添加一個新表,名字為first ws1.write(0,0,'名稱') ws1.write(0,1,'播放數(shù)') ws1.write(0,2,'追番人數(shù) ') ws1.write(0,3,' 彈幕數(shù)') ws1.write(0,4,'點贊數(shù)量') ws1.write(0,5,'投幣數(shù)') row = 1 #寫入的起始行 col = 0 #寫入的起始列 #通過row和col的變化實現(xiàn)指向單元格位置的變化 k = 1 for lines in f: a = lines.split(',') #txt文件中每行的內(nèi)容按逗號分割并存入數(shù)組中 k+=1 for i in range(len(a)): ws1.write(row, col ,a[i])#向Excel文件中寫入每一項 col += 1 row += 1 col = 0 wb.save("數(shù)據(jù)表.xls") if __name__ == "__main__": writeinexcel()
效果圖,今天你有學費了嗎?
python 獲取一大段文本之間兩個關鍵字之間的內(nèi)容
import re class match2Words(object): lines=0 def __init__(self,path,word1,word2): self.path = path self.word1 = word1 self.word2 = word2 def key_match(self): with open(self.path,'rb') as f: buffer = f.read() pattern = re.compile(self.word1+b'(.*?)'+self.word2,re.S) result = pattern.findall(buffer) if result != []: print(result) #self.lines +=1 #print("匹配到的行數(shù):",self.lines) else: print("沒有找到你輸入的關鍵字") path = input("F:/log.lammps") word1 = "Step Temp TotEng PotEng KinEng Pxx Pyy Pzz Lx Ly Lz v_sxx v_syy v_szz v_sxyxy v_sxzxz v_szyzy" word2 = b"end" matchWords = match2Words(path, word1,word2) matchWords.key_match()
總結
到此這篇關于利用Python將txt文件錄入Excel表格的文章就介紹到這了,更多相關Python txt文件錄入Excel內(nèi)容請搜索服務器之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/yuwoxinanA3/article/details/121583669