首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

批量處理文本文件:Python/Perl 實現按比例提取內容(90%/80%/70%)

     編輯:程式設計綜合問答

需求場景

目錄下數百個 TXT 文件,內容為空格分隔的拼音。需批量生成新文件,分別保留原內容的 90%、80%、70%(按行或按 Token 數)。

Python 實現(推薦,可讀性強、生態豐富)

import os, random, glob

def extract_ratio(src_dir, dst_dir, ratios=[0.9, 0.8, 0.7]):
    os.makedirs(dst_dir, exist_ok=True)
    for filepath in glob.glob(os.path.join(src_dir, '*.txt')):
        with open(filepath, 'r', encoding='utf-8') as f:
            tokens = f.read().split()
        n = len(tokens)
        for r in ratios:
            keep = int(n * r)
            # 方案 A:順序保留前 keep 個
            sampled = tokens[:keep]
            # 方案 B:隨機無放回採樣(需打亂順序)
            # sampled = random.sample(tokens, keep)
            base = os.path.basename(filepath)
            name, ext = os.path.splitext(base)
            out_name = f"{name}_p{int(r*100)}{ext}"
            with open(os.path.join(dst_dir, out_name), 'w', encoding='utf-8') as out:
                out.write(' '.join(sampled))
        print(f"Processed: {filepath}")

if __name__ == '__main__':
    extract_ratio('./source_txt', './extracted_txt')

Perl 一行命令(適合熟手快速處理)

# 保留前 90% tokens
perl -e 'open IN,"<,$f"; @t=split/\\s+/,; $k=int(@t*0.9); print join" ",@t[0..$k-1]' source.txt > dest_90.txt

關鍵決策點

  • 保留順序 vs 打亂順序:語言模型訓練通常需打亂;語料完整性驗證則保留順序。
  • 按行 vs 按 Token:拼音空格分隔,按 Token 更精確;若每行一句,按行更快。
  • 編碼統一:指定 UTF-8,避免中文亂碼。
  • 大文件流式處理:單文件超過內存時,需流式讀寫或分塊處理。

Python 腳本可直接擴展為並行處理、進度條、日誌記錄,適合生產環境批量任務。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved