File size: 2,439 Bytes
3d27cfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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                             # n-gram 短语长度
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()

# === 生成 n-gram (保持不变) ===
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:
    # 1. 处理 chosen 列表
    chosen_conversations = item.get("chosen", [])
    for msg in chosen_conversations:
        # 只检查 role 为 assistant 的内容
        if msg.get("role") == "assistant":
            content = msg.get("content", "")
            tokens = clean_and_tokenize(content)
            chosen_phrases.extend(get_ngrams(tokens, n))

    # 2. 处理 rejected 列表 (注意: 样本中键名为 "rejected")
    rejected_conversations = item.get("rejected", [])
    for msg in rejected_conversations:
        # 只检查 role 为 assistant 的内容
        if msg.get("role") == "assistant":
            content = msg.get("content", "")
            tokens = clean_and_tokenize(content)
            reject_phrases.extend(get_ngrams(tokens, n))

# === 统计 n-gram 频率 ===
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}")