1、導(dǎo)入txt文件
f = open(r"D:\0-12 化雪裝置\測(cè)雪儀\4-程序\20210520184832.txt","r")
strr = f.read()
注意:加r的原因是避免轉(zhuǎn)義符的誤解
2、定位目標(biāo)數(shù)據(jù)
! 正則表達(dá)式
推薦官網(wǎng),用來(lái)檢驗(yàn)自己的正則表達(dá)式是否正確:
菜鳥(niǎo)工具
相關(guān)函數(shù)庫(kù)和函數(shù)有:
import re、re.findall、re.search
h=re.findall(r'(Temp:)(.+)',strr)
h_new=list(map(list,h))
hly.append(round(float(re.search(r'([0-9]*[.][0-9]*)',w).group(0)),2))
h(tuple格式的,不可以改)
h_new
hly
目的:不斷在hly內(nèi)加入新的元素,要求元素是浮點(diǎn)型,小數(shù)位數(shù)為2位,w為尋找的總體,
re.search需要添加 **.group(?)**進(jìn)行輸出
float表示變成浮點(diǎn)型
round表示變成2位有效數(shù)字
!切割數(shù)組
o=[]
oo=[]
#合并+切割
for hi in h_new:
hi[1]=hi[0]+hi[1]
del hi[0]
for hii in hi:
o.append(hii.split(','))
#按照項(xiàng)目切割好的數(shù)據(jù)
for oi in o:
for oii in oi:
oo.append(oii.split(':'))
注意:split只能針對(duì)單個(gè)字符串,因此多用**for ?? in ??**來(lái)依次提出目標(biāo)字符串,進(jìn)行循環(huán)判斷
3、制作目標(biāo)格式
! 改成字典形式
keys=[]
values=[]
for i in oo:
keys.append(i[0])
values.append(i[1])
content={} #定義字典
k=0
for i in oo:
keyy=i[0]
k=k+1
if keyy not in content:
content[keyy]=[i[1]] #字典【索引】=值
else:
content[keyy].append(i[1])
! 改成DataFrame格式
data=pd.DataFrame(content,index=time) #content是指字典,index為索引
4、導(dǎo)出為Excel
data.to_excel('data.xls')
基礎(chǔ)復(fù)習(xí):
1、字符串分割
con=cont.split('\n')
2、正則表達(dá)式:[A-Za-z]+ 表示所有英文字符
3、字典定義的經(jīng)典方法:
提出字典的行名稱文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-409790.html
4、用np.array轉(zhuǎn)為可計(jì)算的數(shù)組
5、修改字典的行索引名字文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-409790.html
踩雷&報(bào)錯(cuò)
- 定義變量時(shí),變量名與內(nèi)置函數(shù)名字一樣(eg:str 報(bào)錯(cuò):
- 在網(wǎng)站上的正則表達(dá)式和python中的還是有些許不同,比如要外加( ),在前邊要加r
- 要善于定義函數(shù)!
到了這里,關(guān)于提取txt文件中指定數(shù)據(jù)至excel中(python)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!