借助ChatGPT進行數據清洗
原創在很多實際工作情況下,通過python等工具進行內容爬取,爬取的數據到本地后并不可用,需要進行清洗,清洗后導入到mysql數據庫進行數據分析。對于少量文件可以刪除http頭信息后,另存為json文件,通過mysql的一些客戶端程序直接導入,但對于成百上千個,甚至超過10萬的json文件處理就比較麻煩,本文基于超過數萬json文件的批量處理進行探索,數分鐘解決了數據清洗。
一、程序功能設計
1.3-用戶列表目錄存放burpsuite爬取的數據。
2.爬取數據的格式為json文件
3.爬取的文件帶有http頭內容,通過記事本等編輯器打開顯示頭文件內容為15行。
4.需要刪除每一個文件中的前15行。
5.對所有目錄下的文件命名為txt文件,處理完畢后命名為json文件。
6.依次讀取所有json文件,通過逗號分隔列名,保存為out.txt文件。
7.程序處理出錯,繼續運行,且保存出錯信息。
二、實現編程
這是一個 Python 程序,可以將一個目錄中的 JSON 文件轉換成 CSV 格式,然后將其寫入到一個名為 "3-用戶列表.txt" 的文件中,并記錄執行過程中的錯誤信息到 "error.log" 文件中。
程序的主要邏輯如下:
- 獲取目錄中所有的文件(只包括文件),如果沒有任何文件,則拋出異常;
- 遍歷文件,如果文件的后綴不是 ".txt",則重命名文件名字并改變文件名變量的值;
- 讀取文件內容,將前 15 行保留在一個字符串中,剩余部分作為新內容;
- 將新內容寫回文件中;
- 將文件后綴名從 ".txt" 改為 ".json" 并修改文件名變量的值;
- 讀取 JSON 文件的內容,并獲取其中 "data" 中 "list" 數組中的每個元素的 key 值,這些 key 值作為表格的列名,并將這些列名保存到數組 "columns" 中;
- 遍歷 "list" 數組中的每個元素,將每一行的值存入一個數組 "row_values" 中,最后將 "row_values" 中的所有值拼接成一個字符串,以逗號為分隔符,將其保存到數組 "rows" 中;
- 將 "columns" 和 "rows" 寫入到 "3-用戶列表.txt" 文件中。如果該文件的大小為0,那么先寫入 "columns";否則直接寫入 "rows" 內容;
- 打印信息表明某個文件的數據被寫入了 "out.txt" 文件中。
程序運行過程中出現錯誤,不會影響程序的整體執行,而是將錯誤信息記錄到 "error.log" 文件中。
三、不斷優化
優化內容:
- 增加了try-except語句,用于處理可能出現的異常情況;
- 增加了對目錄下是否存在任何文件的判斷,防止在空目錄中運行程序;
- 增加了錯誤提示,如果程序出錯會顯示錯誤信息;
- 代碼整體結構并沒有變化,只是在原有的代碼基礎上增加了一些出錯處理的邏輯。
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("文件{}中的數據已寫入out.txt文件中".format(json_file))
except Exception as e:
error_file.write('文件{}處理出錯:{}\n'.format(file, e))
print('文件{}處理出錯:{}'.format(file, e))
except Exception as e:
print("出錯了:", e)
四、注意事項
1.需要看json數據格式:
data對應list不同的json文件中list不一樣,需要在代碼中進行修改。
2.處理后的文件內容可能存在重復,需要去重以及處理一些臟數據