Download script/ngram_for_repeated.py from bingqin111/data_process_bq: direct link, hf CLI and curl.
- Browser
- Download file 2.28 kB
-
https://huggingface.co/datasets/bingqin111/data_process_bq/resolve/main/script/ngram_for_repeated.py
- Command line
-
hf download hf://datasets/bingqin111/data_process_bq/script/ngram_for_repeated.py
-
curl -L -o ngram_for_repeated.py https://huggingface.co/datasets/bingqin111/data_process_bq/resolve/main/script/ngram_for_repeated.py
2.28 kB
| import json | |
| import re | |
| from collections import Counter | |
| from itertools import islice | |
| # === 配置 === | |
| filename = "/root/test/weitiao/data_processing_hsichen/data_process_bq/data/mistral_group5_redpo_pk.json" #pk语料下载下来的直接转json格式 | |
| model_id = 7746 #模型id | |
| n = 5 # n-gram 短语长度(3表示统计三连词短语) | |
| top_n = 30 # 输出最常见的前多少个短语 | |
| # === 清理与分词函数 === | |
| def clean_and_tokenize(text): | |
| 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 = [] | |
| # === 读取 JSON 文件 === | |
| with open(filename, 'r', encoding='utf-8') as f: | |
| data = json.load(f) | |
| # === 遍历数据 === | |
| for item in data: | |
| chosen_model = item.get("chosen_model") | |
| reject_model = item.get("reject_model") | |
| chosen_text = item.get("chosen", "") | |
| reject_text = item.get("reject", "") | |
| # 统计 chosen | |
| if chosen_model == model_id and isinstance(chosen_text, str): | |
| tokens = clean_and_tokenize(chosen_text) | |
| chosen_phrases.extend(get_ngrams(tokens, n)) | |
| # 统计 reject | |
| if reject_model == model_id and isinstance(reject_text, str): | |
| tokens = clean_and_tokenize(reject_text) | |
| reject_phrases.extend(get_ngrams(tokens, n)) | |
| # === 统计 n-gram 频率 === | |
| chosen_counter = Counter(chosen_phrases) | |
| reject_counter = Counter(reject_phrases) | |
| # === 打印结果 === | |
| print(f"\n=== 模型ID: {model_id} | {n}-gram 高频短语统计 ===") | |
| print(f"共分析 {len(chosen_phrases)} 个 chosen 短语,{len(reject_phrases)} 个 reject 短语。") | |
| print(f"\n chosen_model == {model_id} 的前 {top_n} 个高频短语:") | |
| for phrase, count in islice(chosen_counter.most_common(top_n), top_n): | |
| print(f"{count:>5} × {phrase}") | |
| print(f"\n reject_model == {model_id} 的前 {top_n} 个高频短语:") | |
| for phrase, count in islice(reject_counter.most_common(top_n), top_n): | |
| print(f"{count:>5} × {phrase}") |