自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

利用ChatGPT輔助處理Html數(shù)據(jù)

原創(chuàng)
開發(fā)
使用chatgpt進行輔助編程首先要清晰描述自己需求,生成代碼通過不斷調(diào)試及優(yōu)化,最終完成任務(wù)。有它,對程序員是好事也是壞事。

一、確認功能

請編程實現(xiàn)以下功能:

1.所有html保存在all文件夾下。

2.對all文件下的所有html進行處理,提取表格中的數(shù)據(jù)。

3.自動提取表格頭,列名以逗號進行分割。

4.處理完畢的文件輸出為out+時間格式文件,用于區(qū)別不同時間處理的文件。

二、通過chatgpt來進行編程

圖片

源代碼如下:

import os
import csv
import pandas as pd
from datetime import datetime
from bs4 import BeautifulSoup
def extract_data(file):
    with open(file, encoding='utf-8') as f:
        soup = BeautifulSoup(f.read(), 'html.parser')
        table = soup.find('table')
        if not headers:
            ths = table.find_all('th')
            headers.extend([th.text.strip().replace('\n', '') for th in ths])
        for tr in table.find_all('tr')[1:]:
            tds = tr.find_all(['th', 'td'])
            row = []
            for td in tds:
                text = td.text.strip().replace('\n', '').replace(',', ';')
                row.append(text)
            if len(row) == len(headers):
                rows.append(row)
def write_data(output_file):
    with open(output_file, 'w', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        writer.writerows(rows)
file_dir = 'all'
html_files = [os.path.join(file_dir, f) for f in os.listdir(file_dir) if f.endswith('.html')]
headers = []
rows = []
for file in html_files:
    extract_data(file)
output_file = f"out_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}.csv"
write_data(output_file)
print(f'Data has been saved to {output_file}')

chatgpt給出的解釋:

具體地,我們使用BeautifulSoup庫解析HTML文件,通過查找<table>標簽和其中的<th><td>標簽來提取數(shù)據(jù)。其中,我們使用了一個headers列表來保存表格頭,使用一個rows列表來保存每一行數(shù)據(jù)。

在處理每個HTML文件時,我們首先查找表格頭,并將其添加到headers列表中。隨后,我們依次遍歷表格的每一行,并將其中的數(shù)據(jù)添加到rows列表中,保證了處理結(jié)果的準確性。對于每一行數(shù)據(jù),我們判斷其長度是否與headers列表相等,如果不相等則說明該行數(shù)據(jù)有誤,我們就不予以保存。最終,我們將所有數(shù)據(jù)保存到一個CSV文件中,輸出文件名為out+當前時間.csv,用于區(qū)別不同時間處理的文件。

這樣,我相信這份代碼能夠滿足您的需求。如有任何問題,請隨時和我聯(lián)系。

三、繼續(xù)優(yōu)化

1.提升效率

2.提供進度條顯示

3.要及時保存數(shù)據(jù),處理意外情況發(fā)生

最終代碼如下:

import os
import csv
import pandas as pd
from datetime import datetime
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
def extract_data(file):
    with open(file, encoding='utf-8') as f:
        soup = BeautifulSoup(f.read(), 'html.parser')
        table = soup.find('table')
        if not headers:
            ths = table.find_all('th')
            headers.extend([th.text.strip().replace('\n', '') for th in ths])
        for tr in table.find_all('tr')[1:]:
            tds = tr.find_all(['th', 'td'])
            row = []
            for td in tds:
                text = td.text.strip().replace('\n', '').replace(',', ';')
                row.append(text)
            if len(row) == len(headers):
                rows.append(row)
                # 每處理1000行數(shù)據(jù),就保存當前數(shù)據(jù)
                if len(rows) % 1000 == 0:
                    output_file = f"out_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}_{len(files)}.csv"
                    write_data(output_file)
                    files.append(output_file)
                    rows.clear()
# 將所有CSV文件合并為一個文件
def combine_files(output_file):
    with open(output_file, 'w', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        for file in files:
            with open(file, 'r', encoding='utf-8') as f2:
                reader = csv.reader(f2)
                next(reader)  # 跳過文件頭
                for row in reader:
                    writer.writerow(row)
            os.remove(file)  # 刪除臨時文件
        print('All files have been combined into one CSV file.')
def write_data(output_file):
    with open(output_file, 'w', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        writer.writerows(rows)
file_dir = 'all'
html_files = [os.path.join(file_dir, f) for f in os.listdir(file_dir) if f.endswith('.html')]
headers = []
rows = []
files = []
with ThreadPoolExecutor(max_workers=4) as executor:
    # 使用tqdm為整個map添加進度條,可以同時顯示當前文件和整體進度
    for _ in tqdm(executor.map(extract_data, html_files), total=len(html_files), desc='Extracting data'):
        pass
# 處理剩余數(shù)據(jù),并保存到CSV文件中
if rows:
    output_file = f"out_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}_{len(files)}.csv"
    write_data(output_file)
    files.append(output_file)
# 合并所有CSV文件為一個文件
output_file = f"out_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}.csv"
combine_files(output_file)
print(f'Data has been saved to {output_file}')

執(zhí)行效果:

圖片

責任編輯:龐桂玉 來源: 51CTO
相關(guān)推薦

2023-05-05 19:29:41

2023-03-20 15:44:00

科研AI

2023-09-06 08:00:00

ChatGPT數(shù)據(jù)分析

2022-12-12 12:04:59

ChatGPT代碼軟件

2023-05-05 22:10:05

2016-11-16 18:49:21

2023-10-10 09:08:50

2012-12-06 10:59:51

大數(shù)據(jù)

2023-04-04 22:28:43

2023-12-13 09:00:00

2020-10-29 06:02:44

PythonPandasExcel

2023-11-01 06:56:56

2012-05-18 10:49:36

SAP大數(shù)據(jù)HANA

2017-12-07 16:08:47

數(shù)據(jù)優(yōu)化HTML字符串

2025-02-26 11:25:26

2023-02-01 08:07:39

HTMLChatGPT互聯(lián)網(wǎng)

2016-12-20 16:07:13

Python數(shù)據(jù)預(yù)處理

2023-03-07 16:43:17

ChatGPT軟件人工智能

2023-03-13 22:23:30

2023-07-04 20:15:00

點贊
收藏

51CTO技術(shù)棧公眾號