目錄下數百個 TXT 文件,內容為空格分隔的拼音。需批量生成新文件,分別保留原內容的 90%、80%、70%(按行或按 Token 數)。
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')
# 保留前 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
Python 腳本可直接擴展為並行處理、進度條、日誌記錄,適合生產環境批量任務。