python提取txt中的特定字元工具

2021-10-09 15:39:58 字數 1434 閱讀 7008

由於工作需要需要提取乙個txt檔案中的特定字元:

原始檔案結構如下:

logon_name\":\"xiaoming\",\"display_name\":\"中國小明\",\"user_password\":\"123\",\"org_name

logon_name\":\"xiaohuang\",\"display_name\":\"中國小黃\",\"user_password\":\"456\",\"org_name

logon_name\":\"xiaoming\",\"display_name\":\"中國小明\",\"user_password\":\"123\",\"org_name

只需要提取如下部分

使用os模組提取路徑資訊

使用re正則模組提取

**如下:

import re

import os

#讀入本目錄下檔案

path = os.getcwd(

)#自動讀取本目錄下的txt檔案

filetest = os.listdir(path)

filepath = path +

"\\"

+filetest[0]

txt =

open

(filepath,

'r',encoding=

'utf-8'

).read(

)#提取原始檔案為utf-8編碼ss

#提取過濾字元

result =

""test_txt = re.findall(

"...+display_name"

,txt)

quchong_test_txt =

list

(set

(test_txt)

)#去重,原始資料需要為列表

result =

'\n'

.join(quchong_test_txt)

result_1 = result.replace(

"logon_name\\\":\\\"",""

)result_2 = result_1.replace(

"\\\",\\\"display_name",""

)print

(result_2)

#輸出結果

filename =

'result.txt'

with

open

(filename,

'a')

as file_object:

file_object.write(result_2)

其他參考文章

python提取txt檔案中的資料

從儲存在txt檔案中的30000多條資料當中提取自己需要的資訊,如下圖示例的資料格式,需要提取出now後的數值並儲存在另外乙個txt檔案當中。結果示例 r as f 開啟檔案 data f.read 讀取檔案 path w r c now 1.txt with open path w,w as f ...

python 提取目錄中特定型別的檔案

python使用 os 和 re 模組提取目錄中特定型別的檔案,這兩個模都是安裝python自帶的,所以不需要安裝。思路 使用os庫lilstdir獲取資料夾中的所有檔名,然後帶上資料夾路徑組合成為完整絕對路徑,然後去判斷該路徑檔案的型別,如果是檔案,使用re庫正則相關函式去篩選出特定字尾的檔案 如...

txt檔案中按日期提取資料

old.txt 2695350881 20190204 00250990da50 2553358 714165 0 0 0 0 1549323678 0 n 0 0 0 提取表頭 head n 1 old.txt new.txt按日期提取 可指定多少行,可指定多個日期 檢視某個日期記錄的行數 gre...