Python如何從txt文件中提取特定數據
本段代碼用于,想要從一段txt文件中只提取目標數據的情況。
代碼:
def get_data(txt_path: str = '', epoch: int = 100, target: str = '', target_data_len: int = 5):
num_list = [] # 將提取出來的數據保存到列表,并在最后返回
data = open(txt_path, encoding="utf-8") # 打開文件
str1 = data.read() # 將文件中讀取到的內容轉化為字符串
data.close() # 關閉文件
for i in range(0, epoch):
index = str1.find(target) # 查找字符串str1中str2字符串的位置
num_list.append(float(str1[index+len(target):index+len(target)+target_data_len])) # 將需要的數據提取到列表中
str1 = str1.replace(target, 'xxxx', 1) # 替換掉已經查閱過的地方,' xxxx '表示替換后的內容,1表示在字符串中的替換次數為1
return num_list函數參數解釋:
- txt_path 文件路徑
- epoch 這份文本文件中要提取出的數據個數,默認100
- target 目標數據的前綴
- target_data_len 目標數據的長度,默認為5
返回值,列表數據
使用舉例:
txt文檔內容:
x1:273 test3:477 y4:38489 y1:149 x2:423
x1:274 test3:475 y4:37956 y1:152 x2:422
x1:269 test3:473 y4:38156 y1:152 x2:421
x1:271 test3:471 y4:38156 y1:155 x2:418
x1:272 test3:467 y4:38056 y1:158 x2:416
x1:275 test3:466 y4:37956 y1:161 x2:415
使用:
data_path = "D:/program/test/double_camera_data/x_data.txt" # 提取x1的數據 list_x1 = get_data(data_path, 6, target="x1:", target_data_len=3) # 提取test3的數據 list_test3 = get_data(data_path, 6, target="test3:", target_data_len=3) # 提取y4的數據 list_y4 = get_data(data_path, 6, target="y4:", target_data_len=6) print(list_x1) print(list_test3) print(list_y4)
輸出:
[273.0, 274.0, 269.0, 271.0, 272.0, 275.0]
[477.0, 475.0, 473.0, 471.0, 467.0, 466.0]
[38489.0, 37956.0, 38156.0, 38156.0, 38056.0, 37956.0]
附:Python 從不規(guī)則文本中提取有效信息
背景:從一個混有文字和多個表格的word文檔里,提取表格中有效信息
代碼:
from docx import Document
import numpy as np
import pandas as pd
#讀取文件
doc = Document("文件名.docx")
#讀取表格
tables = doc.tables
#print(len(tables))
rlt = []
flag = 0
for t in tables: #每一個表格
rows = t.rows
for r in rows: #每一行
cols = r.cells
for c in cols: #每一個單元格
if flag != 0:
rlt.append(c.text)
flag = 0
continue
if c.text == "不動產所有權人" or c.text == "不動產權屬證明" or c.text == "項目名稱" or c.text == "項目地址":
flag = 1
nums = len(rlt)
rlt = np.array(rlt).reshape((nums//4,4))
#print(rlt)
df = pd.DataFrame(rlt,columns= ["不動產所有權人" ,"不動產權屬證明" ,"項目名稱","項目地址"])
#print(df)
df.to_excel('rlt.xlsx')總結
到此這篇關于Python如何從txt文件中提取特定數據的文章就介紹到這了,更多相關Python從txt文件提取數據內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python+Tkinter創(chuàng)建一個簡單的鬧鐘程序
這篇文章主要為大家詳細介紹了如何使用 Python 的 Tkinter 庫創(chuàng)建一個簡單的鬧鐘程序,它可以在指定的時間播放一個聲音來提醒你,感興趣的可以學習一下2023-04-04
Python入門教程(四十一)Python的NumPy數組索引
這篇文章主要介紹了Python入門教程(四十一)Python的NumPy數組索引,數組索引是指使用方括號([])來索引數組值,numpy提供了比常規(guī)的python序列更多的索引工具,除了按整數和切片索引之外,數組可以由整數數組索引、布爾索引及花式索引,需要的朋友可以參考下2023-05-05

