Python實(shí)現(xiàn)讀取txt文件并轉(zhuǎn)換為excel的方法示例
本文實(shí)例講述了Python實(shí)現(xiàn)讀取txt文件并轉(zhuǎn)換為excel的方法。分享給大家供大家參考,具體如下:
這里的txt文件內(nèi)容格式為:
892天平天國(guó)定都在?A開封B南京C北京(B)
Python代碼如下:
# coding=utf-8
'''''
main function:主要實(shí)現(xiàn)把txt中的每行數(shù)據(jù)寫入到excel中
'''
#################
#第一次執(zhí)行的代碼
import xlwt #寫入文件
import xlrd #打開excel文件
import os
txtFileName = 'questions.txt'
excelFileName = 'questions.xls'
if os.path.exists(excelFileName):
os.remove(excelFileName)
fopen = open(txtFileName, 'r')
lines = fopen.readlines()
#新建一個(gè)excel文件
file = xlwt.Workbook(encoding='utf-8',style_compression=0)
#新建一個(gè)sheet
sheet = file.add_sheet('data')
############################
#寫入寫入a.txt,a.txt文件有20000行文件
i=0
j=0
for line in lines:
indexA = line.find('A')
questionStr = line[0:indexA]
questionStr.lstrip()
indexB = line.find('B')
answerA = line[indexA:indexB]
indexC = line.find('C')
indexE = line.find('(')
answerB = ''
if indexC>0:
answerB = line[indexB:indexC]
else:
answerB = line[indexB:indexE]
indexD = line.find('D')
answerC = ''
answerD = ''
if indexD>0:
answerC = line[indexC:indexD]
answerD = line[indexD:indexE]
else:
answerC = line[indexC:indexE]
answer = line[line.find('('):line.find(')')]
cindex = 0
questionStrCopy = ''
for c in questionStr:
if cindex<3:
if c>='0' and c<='9':
questionStrCopy = questionStr[cindex+1:]
cindex = cindex + 1
answerA = answerA[1:]
answerB = answerB[1:]
answerC = answerC[1:]
answerD = answerD[1:]
answer = answer.strip('(')
print answer
print questionStrCopy, answerA, answerB, answerC, answerD, answer
questionStrCopy = questionStrCopy.lstrip()
if questionStrCopy=='' or answerA=='' or answer=='':
continue
sheet.write(i, 0 , questionStrCopy)
sheet.write(i, 1 , answerA)
sheet.write(i, 2 , answerB)
sheet.write(i, 3 , answerC)
sheet.write(i, 4 , answerD)
sheet.write(i, 5 , answer)
i = i + 1
file.save(excelFileName)
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python操作Excel表格技巧總結(jié)》、《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Pycharm-community-2020.2.3 社區(qū)版安裝教程圖文詳解
這篇文章主要介紹了Pycharm-community-2020.2.3 社區(qū)版安裝教程圖文詳解,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
python之線程池map()方法傳遞多參數(shù)list
這篇文章主要介紹了python之線程池map()方法傳遞多參數(shù)list問題,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
python中利用zfill方法自動(dòng)給數(shù)字前面補(bǔ)0
python中有一個(gè)zfill方法用來給字符串前面補(bǔ)0,非常不錯(cuò),下面小編給大家分享了實(shí)例代碼,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2018-04-04
我們?yōu)槭裁匆獪p少Python中循環(huán)的使用
這篇文章主要介紹了我們?yōu)槭裁匆獪p少Python中循環(huán)的使用,我將闡述 Python 提供的一些簡(jiǎn)單但是非常有用的結(jié)構(gòu),一些小技巧以及一些我在數(shù)據(jù)科學(xué)工作中遇到的案例。我將討論 Python 中的 for 循環(huán),以及如何盡量避免使用它們,需要的朋友可以參考下2019-07-07

