欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python如何從txt文件中提取特定數(shù)據(jù)

 更新時間:2023年08月17日 08:38:56   作者:六和七  
這篇文章主要給大家介紹了關(guān)于Python如何從txt文件中提取特定數(shù)據(jù)的相關(guān)資料,有時我們會遇到需要按行讀取文本的情況,我們要讀取txt文件獲得數(shù)據(jù),需要的朋友可以參考下

本段代碼用于,想要從一段txt文件中只提取目標(biāo)數(shù)據(jù)的情況。

代碼:

def get_data(txt_path: str = '', epoch: int = 100, target: str = '', target_data_len: int = 5):
    num_list = []  # 將提取出來的數(shù)據(jù)保存到列表,并在最后返回
    data = open(txt_path, encoding="utf-8")  # 打開文件
    str1 = data.read()  # 將文件中讀取到的內(nèi)容轉(zhuǎn)化為字符串
    data.close()  # 關(guān)閉文件
    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]))  # 將需要的數(shù)據(jù)提取到列表中
        str1 = str1.replace(target, 'xxxx', 1)  # 替換掉已經(jīng)查閱過的地方,' xxxx '表示替換后的內(nèi)容,1表示在字符串中的替換次數(shù)為1
    return num_list

函數(shù)參數(shù)解釋:

  • txt_path 文件路徑
  • epoch 這份文本文件中要提取出的數(shù)據(jù)個數(shù),默認(rèn)100
  • target 目標(biāo)數(shù)據(jù)的前綴
  • target_data_len 目標(biāo)數(shù)據(jù)的長度,默認(rèn)為5
    返回值,列表數(shù)據(jù)

使用舉例:

txt文檔內(nèi)容:

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的數(shù)據(jù)
list_x1  = get_data(data_path, 6, target="x1:", target_data_len=3)
# 提取test3的數(shù)據(jù)
list_test3  = get_data(data_path, 6, target="test3:", target_data_len=3)
# 提取y4的數(shù)據(jù)
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 == "不動產(chǎn)所有權(quán)人" or c.text == "不動產(chǎn)權(quán)屬證明" or c.text == "項(xiàng)目名稱" or  c.text == "項(xiàng)目地址":
                flag = 1
nums = len(rlt)
rlt = np.array(rlt).reshape((nums//4,4))
#print(rlt)            
df = pd.DataFrame(rlt,columns= ["不動產(chǎn)所有權(quán)人" ,"不動產(chǎn)權(quán)屬證明" ,"項(xiàng)目名稱","項(xiàng)目地址"])
#print(df)
df.to_excel('rlt.xlsx')

總結(jié)

到此這篇關(guān)于Python如何從txt文件中提取特定數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Python從txt文件提取數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論