forked from sansan0/TrendRadar
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
2549 lines (2148 loc) · 94.2 KB
/
main.py
File metadata and controls
2549 lines (2148 loc) · 94.2 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
import json
import time
import random
from datetime import datetime
import webbrowser
from typing import Dict, List, Tuple, Optional, Union
from pathlib import Path
import os
import requests
import pytz
CONFIG = {
"VERSION": "1.3.0",
"VERSION_CHECK_URL": "https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/version",
"SHOW_VERSION_UPDATE": True, # 控制显示版本更新提示,改成 False 将不接受新版本提示
"FEISHU_MESSAGE_SEPARATOR": "━━━━━━━━━━━━━━━━━━━", # feishu消息分割线
"REQUEST_INTERVAL": 1000, # 请求间隔(毫秒)
"REPORT_TYPE": "daily", # 报告类型: "current"|"daily"|"both"
"RANK_THRESHOLD": 5, # 排名高亮阈值
"USE_PROXY": True, # 是否启用代理
"DEFAULT_PROXY": "http://127.0.0.1:10086",
"ENABLE_CRAWLER": True, # 是否启用爬取新闻功能,False时直接停止程序
"ENABLE_NOTIFICATION": True, # 是否启用通知功能,False时不发送手机通知
"MESSAGE_BATCH_SIZE": 4000, # 消息分批大小(字节)
"BATCH_SEND_INTERVAL": 1, # 批次发送间隔(秒)
# 飞书机器人的 webhook URL
"FEISHU_WEBHOOK_URL": "",
# 钉钉机器人的 webhook URL
"DINGTALK_WEBHOOK_URL": "",
# 企业微信机器人的 webhook URL
"WEWORK_WEBHOOK_URL": "",
# Telegram 要填两个
"TELEGRAM_BOT_TOKEN": "",
"TELEGRAM_CHAT_ID": "",
# 用于让关注度更高的新闻在更前面显示,这里是权重排序配置,合起来是 1 就行
"WEIGHT_CONFIG": {
"RANK_WEIGHT": 0.6, # 排名
"FREQUENCY_WEIGHT": 0.3, # 频次
"HOTNESS_WEIGHT": 0.1, # 热度
},
}
class TimeHelper:
"""时间处理工具"""
@staticmethod
def get_beijing_time() -> datetime:
return datetime.now(pytz.timezone("Asia/Shanghai"))
@staticmethod
def format_date_folder() -> str:
return TimeHelper.get_beijing_time().strftime("%Y年%m月%d日")
@staticmethod
def format_time_filename() -> str:
return TimeHelper.get_beijing_time().strftime("%H时%M分")
class VersionChecker:
"""版本检查工具"""
@staticmethod
def parse_version(version_str: str) -> Tuple[int, int, int]:
"""解析版本号字符串为元组"""
try:
parts = version_str.strip().split(".")
if len(parts) != 3:
raise ValueError("版本号格式不正确")
return tuple(int(part) for part in parts)
except (ValueError, AttributeError):
print(f"无法解析版本号: {version_str}")
return (0, 0, 0)
@staticmethod
def compare_versions(current: str, remote: str) -> int:
"""比较版本号"""
current_tuple = VersionChecker.parse_version(current)
remote_tuple = VersionChecker.parse_version(remote)
if current_tuple < remote_tuple:
return -1 # 需要更新
elif current_tuple > remote_tuple:
return 1 # 当前版本更新
else:
return 0 # 版本相同
@staticmethod
def check_for_updates(
current_version: str,
version_url: str,
proxy_url: Optional[str] = None,
timeout: int = 10,
) -> Tuple[bool, Optional[str]]:
"""检查是否有新版本"""
try:
proxies = None
if proxy_url:
proxies = {"http": proxy_url, "https": proxy_url}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Accept": "text/plain, */*",
"Cache-Control": "no-cache",
}
response = requests.get(
version_url, proxies=proxies, headers=headers, timeout=timeout
)
response.raise_for_status()
remote_version = response.text.strip()
print(f"当前版本: {current_version}, 远程版本: {remote_version}")
comparison = VersionChecker.compare_versions(
current_version, remote_version
)
need_update = comparison == -1
return need_update, remote_version if need_update else None
except Exception as e:
print(f"版本检查失败: {e}")
return False, None
class FileHelper:
"""文件操作工具"""
@staticmethod
def ensure_directory_exists(directory: str) -> None:
Path(directory).mkdir(parents=True, exist_ok=True)
@staticmethod
def get_output_path(subfolder: str, filename: str) -> str:
date_folder = TimeHelper.format_date_folder()
output_dir = Path("output") / date_folder / subfolder
FileHelper.ensure_directory_exists(str(output_dir))
return str(output_dir / filename)
class DataFetcher:
"""数据获取器"""
def __init__(self, proxy_url: Optional[str] = None):
self.proxy_url = proxy_url
def fetch_data(
self,
id_info: Union[str, Tuple[str, str]],
max_retries: int = 2,
min_retry_wait: int = 3,
max_retry_wait: int = 5,
) -> Tuple[Optional[str], str, str]:
"""获取指定ID数据,支持重试"""
if isinstance(id_info, tuple):
id_value, alias = id_info
else:
id_value = id_info
alias = id_value
url = f"https://newsnow.busiyi.world/api/s?id={id_value}&latest"
proxies = None
if self.proxy_url:
proxies = {"http": self.proxy_url, "https": self.proxy_url}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Connection": "keep-alive",
"Cache-Control": "no-cache",
}
retries = 0
while retries <= max_retries:
try:
response = requests.get(
url, proxies=proxies, headers=headers, timeout=10
)
response.raise_for_status()
data_text = response.text
data_json = json.loads(data_text)
status = data_json.get("status", "未知")
if status not in ["success", "cache"]:
raise ValueError(f"响应状态异常: {status}")
status_info = "最新数据" if status == "success" else "缓存数据"
print(f"获取 {id_value} 成功({status_info})")
return data_text, id_value, alias
except Exception as e:
retries += 1
if retries <= max_retries:
base_wait = random.uniform(min_retry_wait, max_retry_wait)
additional_wait = (retries - 1) * random.uniform(1, 2)
wait_time = base_wait + additional_wait
print(f"请求 {id_value} 失败: {e}. {wait_time:.2f}秒后重试...")
time.sleep(wait_time)
else:
print(f"请求 {id_value} 失败: {e}")
return None, id_value, alias
return None, id_value, alias
def crawl_websites(
self,
ids_list: List[Union[str, Tuple[str, str]]],
request_interval: int = CONFIG["REQUEST_INTERVAL"],
) -> Tuple[Dict, Dict, List]:
"""爬取多个网站数据"""
results = {}
id_to_alias = {}
failed_ids = []
for i, id_info in enumerate(ids_list):
if isinstance(id_info, tuple):
id_value, alias = id_info
else:
id_value = id_info
alias = id_value
id_to_alias[id_value] = alias
response, _, _ = self.fetch_data(id_info)
if response:
try:
data = json.loads(response)
results[id_value] = {}
for index, item in enumerate(data.get("items", []), 1):
title = item["title"]
url = item.get("url", "")
mobile_url = item.get("mobileUrl", "")
if title in results[id_value]:
results[id_value][title]["ranks"].append(index)
else:
results[id_value][title] = {
"ranks": [index],
"url": url,
"mobileUrl": mobile_url,
}
except json.JSONDecodeError:
print(f"解析 {id_value} 响应失败")
failed_ids.append(id_value)
except Exception as e:
print(f"处理 {id_value} 数据出错: {e}")
failed_ids.append(id_value)
else:
failed_ids.append(id_value)
if i < len(ids_list) - 1:
actual_interval = request_interval + random.randint(-10, 20)
actual_interval = max(50, actual_interval)
time.sleep(actual_interval / 1000)
print(f"成功: {list(results.keys())}, 失败: {failed_ids}")
return results, id_to_alias, failed_ids
class DataProcessor:
"""数据处理器"""
@staticmethod
def detect_latest_new_titles(id_to_alias: Dict) -> Dict:
"""检测当日最新批次的新增标题"""
date_folder = TimeHelper.format_date_folder()
txt_dir = Path("output") / date_folder / "txt"
if not txt_dir.exists():
return {}
files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
if len(files) < 2:
# 如果只有一个文件(第一次爬取),没有"新增"的概念,返回空字典
return {}
latest_file = files[-1]
latest_titles = DataProcessor._parse_file_titles(latest_file)
# 汇总历史标题
historical_titles = {}
for file_path in files[:-1]:
historical_data = DataProcessor._parse_file_titles(file_path)
for source_name, titles_data in historical_data.items():
if source_name not in historical_titles:
historical_titles[source_name] = set()
for title in titles_data.keys():
historical_titles[source_name].add(title)
# 找出新增标题
new_titles = {}
for source_name, latest_source_titles in latest_titles.items():
historical_set = historical_titles.get(source_name, set())
source_new_titles = {}
for title, title_data in latest_source_titles.items():
if title not in historical_set:
source_new_titles[title] = title_data
if source_new_titles:
source_id = None
for id_val, alias in id_to_alias.items():
if alias == source_name:
source_id = id_val
break
if source_id:
new_titles[source_id] = source_new_titles
return new_titles
@staticmethod
def _parse_file_titles(file_path: Path) -> Dict:
"""解析单个txt文件的标题数据"""
titles_by_source = {}
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
sections = content.split("\n\n")
for section in sections:
if not section.strip() or "==== 以下ID请求失败 ====" in section:
continue
lines = section.strip().split("\n")
if len(lines) < 2:
continue
source_name = lines[0].strip()
titles_by_source[source_name] = {}
for line in lines[1:]:
if line.strip():
try:
title_part = line.strip()
rank = None
# 提取排名
if (
". " in title_part
and title_part.split(". ")[0].isdigit()
):
rank_str, title_part = title_part.split(". ", 1)
rank = int(rank_str)
# 提取MOBILE URL
mobile_url = ""
if " [MOBILE:" in title_part:
title_part, mobile_part = title_part.rsplit(
" [MOBILE:", 1
)
if mobile_part.endswith("]"):
mobile_url = mobile_part[:-1]
# 提取URL
url = ""
if " [URL:" in title_part:
title_part, url_part = title_part.rsplit(" [URL:", 1)
if url_part.endswith("]"):
url = url_part[:-1]
title = title_part.strip()
ranks = [rank] if rank is not None else [1]
titles_by_source[source_name][title] = {
"ranks": ranks,
"url": url,
"mobileUrl": mobile_url,
}
except Exception as e:
print(f"解析标题行出错: {line}, 错误: {e}")
return titles_by_source
@staticmethod
def save_titles_to_file(results: Dict, id_to_alias: Dict, failed_ids: List) -> str:
"""保存标题到文件"""
file_path = FileHelper.get_output_path(
"txt", f"{TimeHelper.format_time_filename()}.txt"
)
with open(file_path, "w", encoding="utf-8") as f:
for id_value, title_data in results.items():
display_name = id_to_alias.get(id_value, id_value)
f.write(f"{display_name}\n")
# 按排名排序标题
sorted_titles = []
for title, info in title_data.items():
if isinstance(info, dict):
ranks = info.get("ranks", [])
url = info.get("url", "")
mobile_url = info.get("mobileUrl", "")
else:
ranks = info if isinstance(info, list) else []
url = ""
mobile_url = ""
rank = ranks[0] if ranks else 1
sorted_titles.append((rank, title, url, mobile_url))
sorted_titles.sort(key=lambda x: x[0])
for rank, title, url, mobile_url in sorted_titles:
line = f"{rank}. {title}"
if url:
line += f" [URL:{url}]"
if mobile_url:
line += f" [MOBILE:{mobile_url}]"
f.write(line + "\n")
f.write("\n")
if failed_ids:
f.write("==== 以下ID请求失败 ====\n")
for id_value in failed_ids:
display_name = id_to_alias.get(id_value, id_value)
f.write(f"{display_name} (ID: {id_value})\n")
return file_path
@staticmethod
def load_frequency_words(
frequency_file: str = "frequency_words.txt",
) -> Tuple[List[Dict], List[str]]:
"""加载频率词配置"""
frequency_path = Path(frequency_file)
if not frequency_path.exists():
print(f"频率词文件 {frequency_file} 不存在")
return [], []
with open(frequency_path, "r", encoding="utf-8") as f:
content = f.read()
word_groups = [
group.strip() for group in content.split("\n\n") if group.strip()
]
processed_groups = []
filter_words = []
for group in word_groups:
words = [word.strip() for word in group.split("\n") if word.strip()]
group_required_words = []
group_normal_words = []
group_filter_words = []
for word in words:
if word.startswith("!"):
filter_words.append(word[1:])
group_filter_words.append(word[1:])
elif word.startswith("+"):
group_required_words.append(word[1:])
else:
group_normal_words.append(word)
if group_required_words or group_normal_words:
if group_normal_words:
group_key = " ".join(group_normal_words)
else:
group_key = " ".join(group_required_words)
processed_groups.append(
{
"required": group_required_words,
"normal": group_normal_words,
"group_key": group_key,
}
)
return processed_groups, filter_words
@staticmethod
def read_all_today_titles() -> Tuple[Dict, Dict, Dict]:
"""读取当天所有标题文件"""
date_folder = TimeHelper.format_date_folder()
txt_dir = Path("output") / date_folder / "txt"
if not txt_dir.exists():
return {}, {}, {}
all_results = {}
id_to_alias = {}
title_info = {}
files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
for file_path in files:
time_info = file_path.stem
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
sections = content.split("\n\n")
for section in sections:
if not section.strip() or "==== 以下ID请求失败 ====" in section:
continue
lines = section.strip().split("\n")
if len(lines) < 2:
continue
source_name = lines[0].strip()
title_data = {}
for line in lines[1:]:
if line.strip():
try:
rank = None
title_part = line.strip()
# 提取行首的排名数字
if (
". " in title_part
and title_part.split(". ")[0].isdigit()
):
parts = title_part.split(". ", 1)
rank = int(parts[0])
title_part = parts[1]
# 提取 MOBILE URL
mobile_url = ""
if " [MOBILE:" in title_part:
title_part, mobile_part = title_part.rsplit(
" [MOBILE:", 1
)
if mobile_part.endswith("]"):
mobile_url = mobile_part[:-1]
# 提取 URL
url = ""
if " [URL:" in title_part:
title_part, url_part = title_part.rsplit(
" [URL:", 1
)
if url_part.endswith("]"):
url = url_part[:-1]
title = title_part.strip()
ranks = [rank] if rank is not None else [1]
title_data[title] = {
"ranks": ranks,
"url": url,
"mobileUrl": mobile_url,
}
except Exception as e:
print(f"解析标题行出错: {line}, 错误: {e}")
DataProcessor._process_source_data(
source_name,
title_data,
time_info,
all_results,
title_info,
id_to_alias,
)
# 转换为ID格式
id_results = {}
id_title_info = {}
for name, titles in all_results.items():
for id_value, alias in id_to_alias.items():
if alias == name:
id_results[id_value] = titles
id_title_info[id_value] = title_info[name]
break
return id_results, id_to_alias, id_title_info
@staticmethod
def _process_source_data(
source_name: str,
title_data: Dict,
time_info: str,
all_results: Dict,
title_info: Dict,
id_to_alias: Dict,
) -> None:
"""处理来源数据,合并重复标题"""
if source_name not in all_results:
all_results[source_name] = title_data
if source_name not in title_info:
title_info[source_name] = {}
for title, data in title_data.items():
ranks = data.get("ranks", [])
url = data.get("url", "")
mobile_url = data.get("mobileUrl", "")
title_info[source_name][title] = {
"first_time": time_info,
"last_time": time_info,
"count": 1,
"ranks": ranks,
"url": url,
"mobileUrl": mobile_url,
}
reversed_id = source_name.lower().replace(" ", "-")
id_to_alias[reversed_id] = source_name
else:
for title, data in title_data.items():
ranks = data.get("ranks", [])
url = data.get("url", "")
mobile_url = data.get("mobileUrl", "")
if title not in all_results[source_name]:
all_results[source_name][title] = {
"ranks": ranks,
"url": url,
"mobileUrl": mobile_url,
}
title_info[source_name][title] = {
"first_time": time_info,
"last_time": time_info,
"count": 1,
"ranks": ranks,
"url": url,
"mobileUrl": mobile_url,
}
else:
existing_data = all_results[source_name][title]
existing_ranks = existing_data.get("ranks", [])
existing_url = existing_data.get("url", "")
existing_mobile_url = existing_data.get("mobileUrl", "")
merged_ranks = existing_ranks.copy()
for rank in ranks:
if rank not in merged_ranks:
merged_ranks.append(rank)
all_results[source_name][title] = {
"ranks": merged_ranks,
"url": existing_url or url,
"mobileUrl": existing_mobile_url or mobile_url,
}
title_info[source_name][title]["last_time"] = time_info
title_info[source_name][title]["ranks"] = merged_ranks
title_info[source_name][title]["count"] += 1
if not title_info[source_name][title].get("url"):
title_info[source_name][title]["url"] = url
if not title_info[source_name][title].get("mobileUrl"):
title_info[source_name][title]["mobileUrl"] = mobile_url
class StatisticsCalculator:
"""统计计算器"""
@staticmethod
def calculate_news_weight(
title_data: Dict, rank_threshold: int = CONFIG["RANK_THRESHOLD"]
) -> float:
"""计算新闻权重,用于排序"""
ranks = title_data.get("ranks", [])
if not ranks:
return 0.0
count = title_data.get("count", len(ranks))
weight_config = CONFIG["WEIGHT_CONFIG"]
# 排名权重:Σ(11 - min(rank, 10)) / 出现次数
rank_scores = []
for rank in ranks:
score = 11 - min(rank, 10)
rank_scores.append(score)
rank_weight = sum(rank_scores) / len(ranks) if ranks else 0
# 频次权重:min(出现次数, 10) × 10
frequency_weight = min(count, 10) * 10
# 热度加成:高排名次数 / 总出现次数 × 100
high_rank_count = sum(1 for rank in ranks if rank <= rank_threshold)
hotness_ratio = high_rank_count / len(ranks) if ranks else 0
hotness_weight = hotness_ratio * 100
# 综合权重计算
total_weight = (
rank_weight * weight_config["RANK_WEIGHT"]
+ frequency_weight * weight_config["FREQUENCY_WEIGHT"]
+ hotness_weight * weight_config["HOTNESS_WEIGHT"]
)
return total_weight
@staticmethod
def sort_titles_by_weight(
titles_list: List[Dict], rank_threshold: int = CONFIG["RANK_THRESHOLD"]
) -> List[Dict]:
"""按权重对新闻标题列表进行排序"""
def get_sort_key(title_data):
weight = StatisticsCalculator.calculate_news_weight(
title_data, rank_threshold
)
ranks = title_data.get("ranks", [])
count = title_data.get("count", 1)
# 主要按权重排序,权重相同时按最高排名排序,再相同时按出现次数排序
min_rank = min(ranks) if ranks else 999
return (-weight, min_rank, -count)
return sorted(titles_list, key=get_sort_key)
@staticmethod
def _matches_word_groups(
title: str, word_groups: List[Dict], filter_words: List[str]
) -> bool:
"""检查标题是否匹配词组规则"""
title_lower = title.lower()
# 过滤词检查
if any(filter_word.lower() in title_lower for filter_word in filter_words):
return False
# 词组匹配检查
for group in word_groups:
required_words = group["required"]
normal_words = group["normal"]
# 必须词检查
if required_words:
all_required_present = all(
req_word.lower() in title_lower for req_word in required_words
)
if not all_required_present:
continue
# 普通词检查
if normal_words:
any_normal_present = any(
normal_word.lower() in title_lower for normal_word in normal_words
)
if not any_normal_present:
continue
return True
return False
@staticmethod
def count_word_frequency(
results: Dict,
word_groups: List[Dict],
filter_words: List[str],
id_to_alias: Dict,
title_info: Optional[Dict] = None,
rank_threshold: int = CONFIG["RANK_THRESHOLD"],
new_titles: Optional[Dict] = None,
) -> Tuple[List[Dict], int]:
"""统计词频,支持必须词、频率词、过滤词,并标记新增标题"""
word_stats = {}
total_titles = 0
processed_titles = {}
if title_info is None:
title_info = {}
if new_titles is None:
new_titles = {}
for group in word_groups:
group_key = group["group_key"]
word_stats[group_key] = {"count": 0, "titles": {}}
for source_id, titles_data in results.items():
total_titles += len(titles_data)
if source_id not in processed_titles:
processed_titles[source_id] = {}
for title, title_data in titles_data.items():
if title in processed_titles.get(source_id, {}):
continue
# 使用统一的匹配逻辑
if not StatisticsCalculator._matches_word_groups(
title, word_groups, filter_words
):
continue
source_ranks = title_data.get("ranks", [])
source_url = title_data.get("url", "")
source_mobile_url = title_data.get("mobileUrl", "")
# 找到匹配的词组
title_lower = title.lower()
for group in word_groups:
required_words = group["required"]
normal_words = group["normal"]
# 再次检查匹配
if required_words:
all_required_present = all(
req_word.lower() in title_lower
for req_word in required_words
)
if not all_required_present:
continue
if normal_words:
any_normal_present = any(
normal_word.lower() in title_lower
for normal_word in normal_words
)
if not any_normal_present:
continue
group_key = group["group_key"]
word_stats[group_key]["count"] += 1
if source_id not in word_stats[group_key]["titles"]:
word_stats[group_key]["titles"][source_id] = []
first_time = ""
last_time = ""
count_info = 1
ranks = source_ranks if source_ranks else []
url = source_url
mobile_url = source_mobile_url
if (
title_info
and source_id in title_info
and title in title_info[source_id]
):
info = title_info[source_id][title]
first_time = info.get("first_time", "")
last_time = info.get("last_time", "")
count_info = info.get("count", 1)
if "ranks" in info and info["ranks"]:
ranks = info["ranks"]
url = info.get("url", source_url)
mobile_url = info.get("mobileUrl", source_mobile_url)
if not ranks:
ranks = [99]
time_display = StatisticsCalculator._format_time_display(
first_time, last_time
)
source_alias = id_to_alias.get(source_id, source_id)
# 修复is_new判断逻辑,添加容错处理
is_new = False
if new_titles and source_id in new_titles:
new_titles_for_source = new_titles[source_id]
if title in new_titles_for_source:
is_new = True
else:
# 如果直接匹配失败,尝试去除首尾空格后匹配
title_stripped = title.strip()
for new_title in new_titles_for_source.keys():
if title_stripped == new_title.strip():
is_new = True
break
word_stats[group_key]["titles"][source_id].append(
{
"title": title,
"source_alias": source_alias,
"first_time": first_time,
"last_time": last_time,
"time_display": time_display,
"count": count_info,
"ranks": ranks,
"rank_threshold": rank_threshold,
"url": url,
"mobileUrl": mobile_url,
"is_new": is_new,
}
)
if source_id not in processed_titles:
processed_titles[source_id] = {}
processed_titles[source_id][title] = True
break
stats = []
for group_key, data in word_stats.items():
all_titles = []
for source_id, title_list in data["titles"].items():
all_titles.extend(title_list)
# 按权重排序标题
sorted_titles = StatisticsCalculator.sort_titles_by_weight(
all_titles, rank_threshold
)
stats.append(
{
"word": group_key,
"count": data["count"],
"titles": sorted_titles,
"percentage": (
round(data["count"] / total_titles * 100, 2)
if total_titles > 0
else 0
),
}
)
stats.sort(key=lambda x: x["count"], reverse=True)
return stats, total_titles
@staticmethod
def _format_rank_base(
ranks: List[int], rank_threshold: int = 5, format_type: str = "html"
) -> str:
"""基础排名格式化方法"""
if not ranks:
return ""
unique_ranks = sorted(set(ranks))
min_rank = unique_ranks[0]
max_rank = unique_ranks[-1]
# 根据格式类型选择不同的标记方式
if format_type == "html":
highlight_start = "<font color='red'><strong>"
highlight_end = "</strong></font>"
elif format_type == "feishu":
highlight_start = "<font color='red'>**"
highlight_end = "**</font>"
elif format_type == "dingtalk":
highlight_start = "**"
highlight_end = "**"
elif format_type == "wework":
highlight_start = "**"
highlight_end = "**"
elif format_type == "telegram":
highlight_start = "<b>"
highlight_end = "</b>"
else:
highlight_start = "**"
highlight_end = "**"
# 格式化排名显示
if min_rank <= rank_threshold:
if min_rank == max_rank:
return f"{highlight_start}[{min_rank}]{highlight_end}"
else:
return f"{highlight_start}[{min_rank} - {max_rank}]{highlight_end}"
else:
if min_rank == max_rank:
return f"[{min_rank}]"
else:
return f"[{min_rank} - {max_rank}]"
@staticmethod
def _format_rank_for_html(ranks: List[int], rank_threshold: int = 5) -> str:
"""格式化HTML排名显示"""
return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "html")
@staticmethod
def _format_rank_for_feishu(ranks: List[int], rank_threshold: int = 5) -> str:
"""格式化飞书排名显示"""
return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "feishu")
@staticmethod
def _format_rank_for_dingtalk(ranks: List[int], rank_threshold: int = 5) -> str:
"""格式化钉钉排名显示"""
return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "dingtalk")
@staticmethod
def _format_rank_for_wework(ranks: List[int], rank_threshold: int = 5) -> str:
"""格式化企业微信排名显示"""
return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "wework")
@staticmethod
def _format_rank_for_telegram(ranks: List[int], rank_threshold: int = 5) -> str:
"""格式化Telegram排名显示"""
return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "telegram")
@staticmethod
def _format_time_display(first_time: str, last_time: str) -> str:
"""格式化时间显示"""
if not first_time:
return ""
if first_time == last_time or not last_time:
return first_time
else:
return f"[{first_time} ~ {last_time}]"
class ReportGenerator:
"""报告生成器"""