Q: hello | A: hello friend.
Q: hi | A: hi friend.
Q: name | A: i am xslm.
Q: sun | A: the sun is warm.
Q: cat | A: a cat can nap.
Q: dog | A: a dog can run.
Q: red | A: red is a color.
Q: blue | A: blue is a color.
Q: learn | A: i learn from text.
Q: code | A: i can learn code.
Q: moon | A: the moon is in the sky.
Q: rain | A: rain is water.
Q: book | A: i can read a book.
Q: tea | A: tea is warm.
Q: bye | A: bye friend.
prepare.py需要親手編寫的完整原始碼
讀取UTF-8、去重、按完整記錄劃分訓練和驗證,避免同樣例子同時出現。
from pathlib import Path
lines = [line.strip() for line in Path('data/raw.txt').read_text(encoding='utf-8').splitlines() if line.strip()]
lines = list(dict.fromkeys(lines))
assert len(lines) >= 5, 'write at least five different Q/A lines'
assert all(' | A:' in line and line.startswith('Q:') for line in lines)
train = [line for i, line in enumerate(lines) if i % 5 != 0]
val = [line for i, line in enumerate(lines) if i % 5 == 0]
for name, rows in [('train', train), ('val', val)]:
text = '\n'.join(row.replace(' | A:', '\nA:') for row in rows) + '\n'
Path('data/' + name + '.txt').write_text(text, encoding='utf-8')
print(name, len(rows))
逐行拆解程式碼
把親手輸入的原始碼分成小段來讀。左邊的數字是檔案中真實的行號。可以對照裡的 line 數字來讀。
prepare.py 讀取原始資料並去重
from pathlib import Pathlines = [line.strip() for line in Path('data/raw.txt').read_text(encoding='utf-8').splitlines() if line.strip()]lines = list(dict.fromkeys(lines))
用 Path(…).read_text(encoding='utf-8') 把整個檔案讀成文字,用 splitlines() 按行分開。推導式 [line.strip() for line in … if line.strip()] 去掉首尾空格並丟棄空行。dict.fromkeys(lines) 把行作為放入來去重, 保持插入順序,所以最先出現的順序原樣保留。用 set 的話,順序每次執行都可能不同,訓練和驗證的劃分可能會變。
prepare.py 格式檢查
assert len(lines) >= 5, 'write at least five different Q/A lines'assert all(' | A:' in line and line.startswith('Q:') for line in lines)
for name, rows in [('train', train), ('val', val)]: text = '\n'.join(row.replace(' | A:', '\nA:') for row in rows) + '\n' Path('data/' + name + '.txt').write_text(text, encoding='utf-8') print(name, len(rows))