借助ChatGPT進(jìn)行數(shù)據(jù)清洗
原創(chuàng)在很多實(shí)際工作情況下,通過python等工具進(jìn)行內(nèi)容爬取,爬取的數(shù)據(jù)到本地后并不可用,需要進(jìn)行清洗,清洗后導(dǎo)入到mysql數(shù)據(jù)庫進(jìn)行數(shù)據(jù)分析。對于少量文件可以刪除http頭信息后,另存為json文件,通過mysql的一些客戶端程序直接導(dǎo)入,但對于成百上千個(gè),甚至超過10萬的json文件處理就比較麻煩,本文基于超過數(shù)萬json文件的批量處理進(jìn)行探索,數(shù)分鐘解決了數(shù)據(jù)清洗。
一、程序功能設(shè)計(jì)
1.3-用戶列表目錄存放burpsuite爬取的數(shù)據(jù)。
2.爬取數(shù)據(jù)的格式為json文件
3.爬取的文件帶有http頭內(nèi)容,通過記事本等編輯器打開顯示頭文件內(nèi)容為15行。
4.需要?jiǎng)h除每一個(gè)文件中的前15行。
5.對所有目錄下的文件命名為txt文件,處理完畢后命名為json文件。
6.依次讀取所有json文件,通過逗號分隔列名,保存為out.txt文件。
7.程序處理出錯(cuò),繼續(xù)運(yùn)行,且保存出錯(cuò)信息。
二、實(shí)現(xiàn)編程
這是一個(gè) Python 程序,可以將一個(gè)目錄中的 JSON 文件轉(zhuǎn)換成 CSV 格式,然后將其寫入到一個(gè)名為 "3-用戶列表.txt" 的文件中,并記錄執(zhí)行過程中的錯(cuò)誤信息到 "error.log" 文件中。
程序的主要邏輯如下:
- 獲取目錄中所有的文件(只包括文件),如果沒有任何文件,則拋出異常;
- 遍歷文件,如果文件的后綴不是 ".txt",則重命名文件名字并改變文件名變量的值;
- 讀取文件內(nèi)容,將前 15 行保留在一個(gè)字符串中,剩余部分作為新內(nèi)容;
- 將新內(nèi)容寫回文件中;
- 將文件后綴名從 ".txt" 改為 ".json" 并修改文件名變量的值;
- 讀取 JSON 文件的內(nèi)容,并獲取其中 "data" 中 "list" 數(shù)組中的每個(gè)元素的 key 值,這些 key 值作為表格的列名,并將這些列名保存到數(shù)組 "columns" 中;
- 遍歷 "list" 數(shù)組中的每個(gè)元素,將每一行的值存入一個(gè)數(shù)組 "row_values" 中,最后將 "row_values" 中的所有值拼接成一個(gè)字符串,以逗號為分隔符,將其保存到數(shù)組 "rows" 中;
- 將 "columns" 和 "rows" 寫入到 "3-用戶列表.txt" 文件中。如果該文件的大小為0,那么先寫入 "columns";否則直接寫入 "rows" 內(nèi)容;
- 打印信息表明某個(gè)文件的數(shù)據(jù)被寫入了 "out.txt" 文件中。
程序運(yùn)行過程中出現(xiàn)錯(cuò)誤,不會影響程序的整體執(zhí)行,而是將錯(cuò)誤信息記錄到 "error.log" 文件中。
三、不斷優(yōu)化
優(yōu)化內(nèi)容:
- 增加了try-except語句,用于處理可能出現(xiàn)的異常情況;
- 增加了對目錄下是否存在任何文件的判斷,防止在空目錄中運(yùn)行程序;
- 增加了錯(cuò)誤提示,如果程序出錯(cuò)會顯示錯(cuò)誤信息;
- 代碼整體結(jié)構(gòu)并沒有變化,只是在原有的代碼基礎(chǔ)上增加了一些出錯(cuò)處理的邏輯。
import os
import json
dir = '3-用戶列表'
try:
all_files = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f))]
if not all_files:
raise Exception('該目錄下不存在任何文件')
with open('error.log', 'a+', encoding='utf-8') as error_file:
for file in all_files:
try:
if not file.endswith('.txt'):
os.rename(os.path.join(dir, file), os.path.join(dir, os.path.splitext(file)[0] + '.txt'))
file = os.path.splitext(file)[0] + '.txt'
with open(os.path.join(dir, file), 'r', encoding='utf-8') as txt_file:
content = txt_file.readlines()
deleted_content = '\n'.join(content[:15])
new_content = ''.join(content[15:])
with open(os.path.join(dir, file), 'w', encoding='utf-8') as txt_file:
txt_file.write(new_content)
json_file = os.path.splitext(file)[0] + '.json'
os.rename(os.path.join(dir, file), os.path.join(dir, json_file))
with open(os.path.join(dir, json_file), 'r', encoding='utf-8') as j_file:
data = json.load(j_file)
columns = list(data['data']['list'][0].keys())
rows = []
for item in data['data']['list']:
row_values = []
for column in columns:
value = str(item[column]).replace('\n','').replace(',','')
row_values.append(value)
rows.append(','.join(row_values))
with open('3-用戶列表.txt', 'a+', encoding='utf-8') as out_file:
if out_file.tell() == 0:
out_file.write(','.join(columns) + '\n')
out_file.write('\n'.join(rows)+'\n')
print("文件{}中的數(shù)據(jù)已寫入out.txt文件中".format(json_file))
except Exception as e:
error_file.write('文件{}處理出錯(cuò):{}\n'.format(file, e))
print('文件{}處理出錯(cuò):{}'.format(file, e))
except Exception as e:
print("出錯(cuò)了:", e)
四、注意事項(xiàng)
1.需要看json數(shù)據(jù)格式:
data對應(yīng)list不同的json文件中l(wèi)ist不一樣,需要在代碼中進(jìn)行修改。
2.處理后的文件內(nèi)容可能存在重復(fù),需要去重以及處理一些臟數(shù)據(jù)