| import json |
| import re |
| from collections import Counter |
| from itertools import islice |
|
|
| filename = "/root/test/weitiao/data_process_bq/data/train4_chatml_closed_numdel.json" |
| n = 5 |
| top_n = 30 |
|
|
| |
| def clean_and_tokenize(text): |
| if not isinstance(text, str): |
| return [] |
| text = text.lower() |
| text = re.sub(r'\d+', '', text) |
| text = re.sub(r'[^a-z\s]', '', text) |
| text = re.sub(r'\s+', ' ', text).strip() |
| return text.split() |
|
|
| |
| def get_ngrams(tokens, n): |
| if len(tokens) < n: |
| return [] |
| return [' '.join(tokens[i:i+n]) for i in range(len(tokens)-n+1)] |
|
|
| chosen_phrases = [] |
| reject_phrases = [] |
|
|
| with open(filename, 'r', encoding='utf-8') as f: |
| data = json.load(f) |
|
|
| |
| for item in data: |
| |
| chosen_conversations = item.get("chosen", []) |
| for msg in chosen_conversations: |
| |
| if msg.get("role") == "assistant": |
| content = msg.get("content", "") |
| tokens = clean_and_tokenize(content) |
| chosen_phrases.extend(get_ngrams(tokens, n)) |
|
|
| |
| rejected_conversations = item.get("rejected", []) |
| for msg in rejected_conversations: |
| |
| if msg.get("role") == "assistant": |
| content = msg.get("content", "") |
| tokens = clean_and_tokenize(content) |
| reject_phrases.extend(get_ngrams(tokens, n)) |
|
|
| |
| chosen_counter = Counter(chosen_phrases) |
| reject_counter = Counter(reject_phrases) |
|
|
| |
| print(f"\n=== {n}-gram 高频短语统计 (仅统计 Assistant 回复) ===") |
| print(f"共分析 {len(chosen_phrases)} 个 chosen 短语,{len(reject_phrases)} 个 rejected 短语。") |
|
|
| print(f"\n Chosen (Assistant) 的前 {top_n} 个高频短语:") |
| for phrase, count in islice(chosen_counter.most_common(top_n), top_n): |
| print(f"{count:>5} × {phrase}") |
|
|
| print(f"\n Rejected (Assistant) 的前 {top_n} 个高频短语:") |
| for phrase, count in islice(reject_counter.most_common(top_n), top_n): |
| print(f"{count:>5} × {phrase}") |