需求:讀取 txt,刪除(1)純數字詞、(2)字母+漢字混合詞、(3)超過 15 字詞、(4).com 網址詞,去首尾空格,只保留漢字詞。
import re
def filter_words(input_file, output_file):
with open(input_file, 'r', encoding='utf-8') as f:
text = f.read()
# 分詞:按空白、標點分割(簡易版,中文建議用 jieba)
words = re.split(r'[\s\u3000,。!?、;:“”‘’《》〈〉【】「」\'\"/\\|`~!@#$%^&*()_+\-=\[\]{};:,.<>?]+', text)
filtered = []
for w in words:
w = w.strip()
if not w: continue
# 1. 純數字
if re.fullmatch(r'\d+', w): continue
# 2. 字母+漢字混合(含字母且含漢字)
if re.search(r'[a-zA-Z]', w) and re.search(r'[\u4e00-\u9fff]', w): continue
# 3. 長度 > 15
if len(w) > 15: continue
# 4. 含 .com
if '.com' in w.lower(): continue
# 只保留漢字詞(至少一個漢字,無字母數字標點)
if re.fullmatch(r'[\u4e00-\u9fff]+', w):
filtered.append(w)
with open(output_file, 'w', encoding='utf-8') as f:
f.write('\n'.join(filtered))
# 使用
filter_words('input.txt', 'output.txt')
文字處理任務**強烈建議用 Python**(`jieba`、`re`、編碼處理成熟),C++ 僅在效能極致要求或嵌入式環境下考慮。