analyzer.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. # coding=utf-8
  2. """
  3. 统计分析模块
  4. 提供新闻统计和分析功能:
  5. - calculate_news_weight: 计算新闻权重
  6. - format_time_display: 格式化时间显示
  7. - count_word_frequency: 统计词频
  8. """
  9. from typing import Dict, List, Tuple, Optional, Callable
  10. from trendradar.core.frequency import matches_word_groups, _word_matches
  11. def calculate_news_weight(
  12. title_data: Dict,
  13. rank_threshold: int,
  14. weight_config: Dict,
  15. ) -> float:
  16. """
  17. 计算新闻权重,用于排序
  18. Args:
  19. title_data: 标题数据,包含 ranks 和 count
  20. rank_threshold: 排名阈值
  21. weight_config: 权重配置 {RANK_WEIGHT, FREQUENCY_WEIGHT, HOTNESS_WEIGHT}
  22. Returns:
  23. float: 计算出的权重值
  24. """
  25. ranks = title_data.get("ranks", [])
  26. if not ranks:
  27. return 0.0
  28. count = title_data.get("count", len(ranks))
  29. # 排名权重:Σ(11 - min(rank, 10)) / 出现次数
  30. rank_scores = []
  31. for rank in ranks:
  32. score = 11 - min(rank, 10)
  33. rank_scores.append(score)
  34. rank_weight = sum(rank_scores) / len(ranks) if ranks else 0
  35. # 频次权重:min(出现次数, 10) × 10
  36. frequency_weight = min(count, 10) * 10
  37. # 热度加成:高排名次数 / 总出现次数 × 100
  38. high_rank_count = sum(1 for rank in ranks if rank <= rank_threshold)
  39. hotness_ratio = high_rank_count / len(ranks) if ranks else 0
  40. hotness_weight = hotness_ratio * 100
  41. total_weight = (
  42. rank_weight * weight_config["RANK_WEIGHT"]
  43. + frequency_weight * weight_config["FREQUENCY_WEIGHT"]
  44. + hotness_weight * weight_config["HOTNESS_WEIGHT"]
  45. )
  46. return total_weight
  47. def format_time_display(
  48. first_time: str,
  49. last_time: str,
  50. convert_time_func: Callable[[str], str],
  51. ) -> str:
  52. """
  53. 格式化时间显示(将 HH-MM 转换为 HH:MM)
  54. Args:
  55. first_time: 首次出现时间
  56. last_time: 最后出现时间
  57. convert_time_func: 时间格式转换函数
  58. Returns:
  59. str: 格式化后的时间显示字符串
  60. """
  61. if not first_time:
  62. return ""
  63. # 转换为显示格式
  64. first_display = convert_time_func(first_time)
  65. last_display = convert_time_func(last_time)
  66. if first_display == last_display or not last_display:
  67. return first_display
  68. else:
  69. return f"[{first_display} ~ {last_display}]"
  70. def count_word_frequency(
  71. results: Dict,
  72. word_groups: List[Dict],
  73. filter_words: List[str],
  74. id_to_name: Dict,
  75. title_info: Optional[Dict] = None,
  76. rank_threshold: int = 3,
  77. new_titles: Optional[Dict] = None,
  78. mode: str = "daily",
  79. global_filters: Optional[List[str]] = None,
  80. weight_config: Optional[Dict] = None,
  81. max_news_per_keyword: int = 0,
  82. sort_by_position_first: bool = False,
  83. is_first_crawl_func: Optional[Callable[[], bool]] = None,
  84. convert_time_func: Optional[Callable[[str], str]] = None,
  85. quiet: bool = False,
  86. ) -> Tuple[List[Dict], int]:
  87. """
  88. 统计词频,支持必须词、频率词、过滤词、全局过滤词,并标记新增标题
  89. Args:
  90. results: 抓取结果 {source_id: {title: title_data}}
  91. word_groups: 词组配置列表
  92. filter_words: 过滤词列表
  93. id_to_name: ID 到名称的映射
  94. title_info: 标题统计信息(可选)
  95. rank_threshold: 排名阈值
  96. new_titles: 新增标题(可选)
  97. mode: 报告模式 (daily/incremental/current)
  98. global_filters: 全局过滤词(可选)
  99. weight_config: 权重配置
  100. max_news_per_keyword: 每个关键词最大显示数量
  101. sort_by_position_first: 是否优先按配置位置排序
  102. is_first_crawl_func: 检测是否是当天第一次爬取的函数
  103. convert_time_func: 时间格式转换函数
  104. quiet: 是否静默模式(不打印日志)
  105. Returns:
  106. Tuple[List[Dict], int]: (统计结果列表, 总标题数)
  107. """
  108. # 默认权重配置
  109. if weight_config is None:
  110. weight_config = {
  111. "RANK_WEIGHT": 0.4,
  112. "FREQUENCY_WEIGHT": 0.3,
  113. "HOTNESS_WEIGHT": 0.3,
  114. }
  115. # 默认时间转换函数
  116. if convert_time_func is None:
  117. convert_time_func = lambda x: x
  118. # 默认首次爬取检测函数
  119. if is_first_crawl_func is None:
  120. is_first_crawl_func = lambda: True
  121. # 如果没有配置词组,创建一个包含所有新闻的虚拟词组
  122. if not word_groups:
  123. print("频率词配置为空,将显示所有新闻")
  124. word_groups = [{"required": [], "normal": [], "group_key": "全部新闻"}]
  125. filter_words = [] # 清空过滤词,显示所有新闻
  126. is_first_today = is_first_crawl_func()
  127. # 确定处理的数据源和新增标记逻辑
  128. if mode == "incremental":
  129. if is_first_today:
  130. # 增量模式 + 当天第一次:处理所有新闻,都标记为新增
  131. results_to_process = results
  132. all_news_are_new = True
  133. else:
  134. # 增量模式 + 当天非第一次:只处理新增的新闻
  135. results_to_process = new_titles if new_titles else {}
  136. all_news_are_new = True
  137. elif mode == "current":
  138. # current 模式:只处理当前时间批次的新闻,但统计信息来自全部历史
  139. if title_info:
  140. latest_time = None
  141. for source_titles in title_info.values():
  142. for title_data in source_titles.values():
  143. last_time = title_data.get("last_time", "")
  144. if last_time:
  145. if latest_time is None or last_time > latest_time:
  146. latest_time = last_time
  147. # 只处理 last_time 等于最新时间的新闻
  148. if latest_time:
  149. results_to_process = {}
  150. for source_id, source_titles in results.items():
  151. if source_id in title_info:
  152. filtered_titles = {}
  153. for title, title_data in source_titles.items():
  154. if title in title_info[source_id]:
  155. info = title_info[source_id][title]
  156. if info.get("last_time") == latest_time:
  157. filtered_titles[title] = title_data
  158. if filtered_titles:
  159. results_to_process[source_id] = filtered_titles
  160. if not quiet:
  161. print(
  162. f"当前榜单模式:最新时间 {latest_time},筛选出 {sum(len(titles) for titles in results_to_process.values())} 条当前榜单新闻"
  163. )
  164. else:
  165. results_to_process = results
  166. else:
  167. results_to_process = results
  168. all_news_are_new = False
  169. else:
  170. # 当日汇总模式:处理所有新闻
  171. results_to_process = results
  172. all_news_are_new = False
  173. total_input_news = sum(len(titles) for titles in results.values())
  174. filter_status = (
  175. "全部显示"
  176. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  177. else "频率词过滤"
  178. )
  179. print(f"当日汇总模式:处理 {total_input_news} 条新闻,模式:{filter_status}")
  180. word_stats = {}
  181. total_titles = 0
  182. processed_titles = {}
  183. matched_new_count = 0
  184. if title_info is None:
  185. title_info = {}
  186. if new_titles is None:
  187. new_titles = {}
  188. for group in word_groups:
  189. group_key = group["group_key"]
  190. word_stats[group_key] = {"count": 0, "titles": {}}
  191. for source_id, titles_data in results_to_process.items():
  192. total_titles += len(titles_data)
  193. if source_id not in processed_titles:
  194. processed_titles[source_id] = {}
  195. for title, title_data in titles_data.items():
  196. if title in processed_titles.get(source_id, {}):
  197. continue
  198. # 使用统一的匹配逻辑
  199. matches_frequency_words = matches_word_groups(
  200. title, word_groups, filter_words, global_filters
  201. )
  202. if not matches_frequency_words:
  203. continue
  204. # 如果是增量模式或 current 模式第一次,统计匹配的新增新闻数量
  205. if (mode == "incremental" and all_news_are_new) or (
  206. mode == "current" and is_first_today
  207. ):
  208. matched_new_count += 1
  209. source_ranks = title_data.get("ranks", [])
  210. source_url = title_data.get("url", "")
  211. source_mobile_url = title_data.get("mobileUrl", "")
  212. # 找到匹配的词组(防御性转换确保类型安全)
  213. title_lower = str(title).lower() if not isinstance(title, str) else title.lower()
  214. for group in word_groups:
  215. required_words = group["required"]
  216. normal_words = group["normal"]
  217. # 如果是"全部新闻"模式,所有标题都匹配第一个(唯一的)词组
  218. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻":
  219. group_key = group["group_key"]
  220. word_stats[group_key]["count"] += 1
  221. if source_id not in word_stats[group_key]["titles"]:
  222. word_stats[group_key]["titles"][source_id] = []
  223. else:
  224. # 原有的匹配逻辑(支持正则语法)
  225. if required_words:
  226. all_required_present = all(
  227. _word_matches(req_item, title_lower)
  228. for req_item in required_words
  229. )
  230. if not all_required_present:
  231. continue
  232. if normal_words:
  233. any_normal_present = any(
  234. _word_matches(normal_item, title_lower)
  235. for normal_item in normal_words
  236. )
  237. if not any_normal_present:
  238. continue
  239. group_key = group["group_key"]
  240. word_stats[group_key]["count"] += 1
  241. if source_id not in word_stats[group_key]["titles"]:
  242. word_stats[group_key]["titles"][source_id] = []
  243. first_time = ""
  244. last_time = ""
  245. count_info = 1
  246. ranks = source_ranks if source_ranks else []
  247. url = source_url
  248. mobile_url = source_mobile_url
  249. rank_timeline = []
  250. # 对于 current 模式,从历史统计信息中获取完整数据
  251. if (
  252. mode == "current"
  253. and title_info
  254. and source_id in title_info
  255. and title in title_info[source_id]
  256. ):
  257. info = title_info[source_id][title]
  258. first_time = info.get("first_time", "")
  259. last_time = info.get("last_time", "")
  260. count_info = info.get("count", 1)
  261. if "ranks" in info and info["ranks"]:
  262. ranks = info["ranks"]
  263. url = info.get("url", source_url)
  264. mobile_url = info.get("mobileUrl", source_mobile_url)
  265. rank_timeline = info.get("rank_timeline", [])
  266. elif (
  267. title_info
  268. and source_id in title_info
  269. and title in title_info[source_id]
  270. ):
  271. info = title_info[source_id][title]
  272. first_time = info.get("first_time", "")
  273. last_time = info.get("last_time", "")
  274. count_info = info.get("count", 1)
  275. if "ranks" in info and info["ranks"]:
  276. ranks = info["ranks"]
  277. url = info.get("url", source_url)
  278. mobile_url = info.get("mobileUrl", source_mobile_url)
  279. rank_timeline = info.get("rank_timeline", [])
  280. if not ranks:
  281. ranks = [99]
  282. time_display = format_time_display(first_time, last_time, convert_time_func)
  283. source_name = id_to_name.get(source_id, source_id)
  284. # 判断是否为新增
  285. is_new = False
  286. if all_news_are_new:
  287. # 增量模式下所有处理的新闻都是新增,或者当天第一次的所有新闻都是新增
  288. is_new = True
  289. elif new_titles and source_id in new_titles:
  290. # 检查是否在新增列表中
  291. new_titles_for_source = new_titles[source_id]
  292. is_new = title in new_titles_for_source
  293. word_stats[group_key]["titles"][source_id].append(
  294. {
  295. "title": title,
  296. "source_name": source_name,
  297. "first_time": first_time,
  298. "last_time": last_time,
  299. "time_display": time_display,
  300. "count": count_info,
  301. "ranks": ranks,
  302. "rank_threshold": rank_threshold,
  303. "url": url,
  304. "mobileUrl": mobile_url,
  305. "is_new": is_new,
  306. "rank_timeline": rank_timeline,
  307. }
  308. )
  309. if source_id not in processed_titles:
  310. processed_titles[source_id] = {}
  311. processed_titles[source_id][title] = True
  312. break
  313. # 最后统一打印汇总信息
  314. if mode == "incremental":
  315. if is_first_today:
  316. total_input_news = sum(len(titles) for titles in results.values())
  317. filter_status = (
  318. "全部显示"
  319. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  320. else "频率词匹配"
  321. )
  322. if not quiet:
  323. print(
  324. f"增量模式:当天第一次爬取,{total_input_news} 条新闻中有 {matched_new_count} 条{filter_status}"
  325. )
  326. else:
  327. if new_titles:
  328. total_new_count = sum(len(titles) for titles in new_titles.values())
  329. filter_status = (
  330. "全部显示"
  331. if len(word_groups) == 1
  332. and word_groups[0]["group_key"] == "全部新闻"
  333. else "匹配频率词"
  334. )
  335. if not quiet:
  336. print(
  337. f"增量模式:{total_new_count} 条新增新闻中,有 {matched_new_count} 条{filter_status}"
  338. )
  339. if matched_new_count == 0 and len(word_groups) > 1:
  340. print("增量模式:没有新增新闻匹配频率词,将不会发送通知")
  341. else:
  342. if not quiet:
  343. print("增量模式:未检测到新增新闻")
  344. elif mode == "current":
  345. total_input_news = sum(len(titles) for titles in results_to_process.values())
  346. if is_first_today:
  347. filter_status = (
  348. "全部显示"
  349. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  350. else "频率词匹配"
  351. )
  352. if not quiet:
  353. print(
  354. f"当前榜单模式:当天第一次爬取,{total_input_news} 条当前榜单新闻中有 {matched_new_count} 条{filter_status}"
  355. )
  356. else:
  357. matched_count = sum(stat["count"] for stat in word_stats.values())
  358. filter_status = (
  359. "全部显示"
  360. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻"
  361. else "频率词匹配"
  362. )
  363. if not quiet:
  364. print(
  365. f"当前榜单模式:{total_input_news} 条当前榜单新闻中有 {matched_count} 条{filter_status}"
  366. )
  367. stats = []
  368. # 创建 group_key 到位置、最大数量、显示名称的映射
  369. group_key_to_position = {
  370. group["group_key"]: idx for idx, group in enumerate(word_groups)
  371. }
  372. group_key_to_max_count = {
  373. group["group_key"]: group.get("max_count", 0) for group in word_groups
  374. }
  375. group_key_to_display_name = {
  376. group["group_key"]: group.get("display_name") for group in word_groups
  377. }
  378. for group_key, data in word_stats.items():
  379. all_titles = []
  380. for source_id, title_list in data["titles"].items():
  381. all_titles.extend(title_list)
  382. # 按权重排序
  383. sorted_titles = sorted(
  384. all_titles,
  385. key=lambda x: (
  386. -calculate_news_weight(x, rank_threshold, weight_config),
  387. min(x["ranks"]) if x["ranks"] else 999,
  388. -x["count"],
  389. ),
  390. )
  391. # 应用最大显示数量限制(优先级:单独配置 > 全局配置)
  392. group_max_count = group_key_to_max_count.get(group_key, 0)
  393. if group_max_count == 0:
  394. # 使用全局配置
  395. group_max_count = max_news_per_keyword
  396. if group_max_count > 0:
  397. sorted_titles = sorted_titles[:group_max_count]
  398. # 优先使用 display_name,否则使用 group_key
  399. display_word = group_key_to_display_name.get(group_key) or group_key
  400. stats.append(
  401. {
  402. "word": display_word,
  403. "count": data["count"],
  404. "position": group_key_to_position.get(group_key, 999),
  405. "titles": sorted_titles,
  406. "percentage": (
  407. round(data["count"] / total_titles * 100, 2)
  408. if total_titles > 0
  409. else 0
  410. ),
  411. }
  412. )
  413. # 根据配置选择排序优先级
  414. if sort_by_position_first:
  415. # 先按配置位置,再按热点条数
  416. stats.sort(key=lambda x: (x["position"], -x["count"]))
  417. else:
  418. # 先按热点条数,再按配置位置(原逻辑)
  419. stats.sort(key=lambda x: (-x["count"], x["position"]))
  420. # 打印过滤后的匹配新闻数
  421. matched_news_count = sum(len(stat["titles"]) for stat in stats if stat["count"] > 0)
  422. if not quiet and mode == "daily":
  423. print(f"当日汇总模式:处理 {total_titles} 条新闻,模式:频率词过滤")
  424. print(f"频率词过滤后:{matched_news_count} 条新闻匹配")
  425. return stats, total_titles
  426. def count_rss_frequency(
  427. rss_items: List[Dict],
  428. word_groups: List[Dict],
  429. filter_words: List[str],
  430. global_filters: Optional[List[str]] = None,
  431. new_items: Optional[List[Dict]] = None,
  432. max_news_per_keyword: int = 0,
  433. sort_by_position_first: bool = False,
  434. timezone: str = "Asia/Shanghai",
  435. rank_threshold: int = 5,
  436. quiet: bool = False,
  437. ) -> Tuple[List[Dict], int]:
  438. """
  439. 按关键词分组统计 RSS 条目(与热榜统计格式一致)
  440. Args:
  441. rss_items: RSS 条目列表,每个条目包含:
  442. - title: 标题
  443. - feed_id: RSS 源 ID
  444. - feed_name: RSS 源名称
  445. - url: 文章链接
  446. - published_at: 发布时间(ISO 格式)
  447. word_groups: 词组配置列表
  448. filter_words: 过滤词列表
  449. global_filters: 全局过滤词(可选)
  450. new_items: 新增条目列表(可选,用于标记 is_new)
  451. max_news_per_keyword: 每个关键词最大显示数量
  452. sort_by_position_first: 是否优先按配置位置排序
  453. timezone: 时区名称(用于时间格式化)
  454. quiet: 是否静默模式
  455. Returns:
  456. Tuple[List[Dict], int]: (统计结果列表, 总条目数)
  457. 统计结果格式与热榜一致:
  458. [
  459. {
  460. "word": "关键词",
  461. "count": 5,
  462. "position": 0,
  463. "titles": [
  464. {
  465. "title": "标题",
  466. "source_name": "Hacker News",
  467. "time_display": "12-29 08:20",
  468. "count": 1,
  469. "ranks": [1], # RSS 用发布时间顺序作为排名
  470. "rank_threshold": 50,
  471. "url": "...",
  472. "mobile_url": "",
  473. "is_new": True/False
  474. }
  475. ],
  476. "percentage": 10.0
  477. }
  478. ]
  479. """
  480. from trendradar.utils.time import format_iso_time_friendly
  481. if not rss_items:
  482. return [], 0
  483. # 如果没有配置词组,创建一个包含所有条目的虚拟词组
  484. if not word_groups:
  485. if not quiet:
  486. print("[RSS] 频率词配置为空,将显示所有 RSS 条目")
  487. word_groups = [{"required": [], "normal": [], "group_key": "全部 RSS"}]
  488. filter_words = []
  489. # 创建新增条目的 URL 集合,用于快速查找
  490. new_urls = set()
  491. if new_items:
  492. for item in new_items:
  493. if item.get("url"):
  494. new_urls.add(item["url"])
  495. # 初始化词组统计
  496. word_stats = {}
  497. for group in word_groups:
  498. group_key = group["group_key"]
  499. word_stats[group_key] = {"count": 0, "titles": []}
  500. total_items = len(rss_items)
  501. processed_urls = set() # 用于去重
  502. # 为每个条目分配一个基于发布时间的"排名"
  503. # 按发布时间排序,最新的排在前面
  504. sorted_items = sorted(
  505. rss_items,
  506. key=lambda x: x.get("published_at", ""),
  507. reverse=True
  508. )
  509. url_to_rank = {item.get("url", ""): idx + 1 for idx, item in enumerate(sorted_items)}
  510. for item in rss_items:
  511. title = item.get("title", "")
  512. url = item.get("url", "")
  513. # 去重
  514. if url and url in processed_urls:
  515. continue
  516. if url:
  517. processed_urls.add(url)
  518. # 使用统一的匹配逻辑
  519. if not matches_word_groups(title, word_groups, filter_words, global_filters):
  520. continue
  521. # 找到匹配的词组
  522. title_lower = title.lower()
  523. for group in word_groups:
  524. required_words = group["required"]
  525. normal_words = group["normal"]
  526. group_key = group["group_key"]
  527. # "全部 RSS" 模式:所有条目都匹配
  528. if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部 RSS":
  529. matched = True
  530. else:
  531. # 检查必须词(支持正则语法)
  532. if required_words:
  533. all_required_present = all(
  534. _word_matches(req_item, title_lower)
  535. for req_item in required_words
  536. )
  537. if not all_required_present:
  538. continue
  539. # 检查普通词(支持正则语法)
  540. if normal_words:
  541. any_normal_present = any(
  542. _word_matches(normal_item, title_lower)
  543. for normal_item in normal_words
  544. )
  545. if not any_normal_present:
  546. continue
  547. matched = True
  548. if matched:
  549. word_stats[group_key]["count"] += 1
  550. # 格式化时间显示
  551. published_at = item.get("published_at", "")
  552. time_display = format_iso_time_friendly(published_at, timezone, include_date=True) if published_at else ""
  553. # 判断是否为新增
  554. is_new = url in new_urls if url else False
  555. # 获取排名(基于发布时间顺序)
  556. rank = url_to_rank.get(url, 99) if url else 99
  557. title_data = {
  558. "title": title,
  559. "source_name": item.get("feed_name", item.get("feed_id", "RSS")),
  560. "time_display": time_display,
  561. "count": 1, # RSS 条目通常只出现一次
  562. "ranks": [rank],
  563. "rank_threshold": rank_threshold,
  564. "url": url,
  565. "mobile_url": "",
  566. "is_new": is_new,
  567. }
  568. word_stats[group_key]["titles"].append(title_data)
  569. break # 一个条目只匹配第一个词组
  570. # 构建统计结果
  571. stats = []
  572. group_key_to_position = {
  573. group["group_key"]: idx for idx, group in enumerate(word_groups)
  574. }
  575. group_key_to_max_count = {
  576. group["group_key"]: group.get("max_count", 0) for group in word_groups
  577. }
  578. group_key_to_display_name = {
  579. group["group_key"]: group.get("display_name") for group in word_groups
  580. }
  581. for group_key, data in word_stats.items():
  582. if data["count"] == 0:
  583. continue
  584. # 按发布时间排序(最新在前)
  585. sorted_titles = sorted(
  586. data["titles"],
  587. key=lambda x: x["ranks"][0] if x["ranks"] else 999
  588. )
  589. # 应用最大显示数量限制
  590. group_max_count = group_key_to_max_count.get(group_key, 0)
  591. if group_max_count == 0:
  592. group_max_count = max_news_per_keyword
  593. if group_max_count > 0:
  594. sorted_titles = sorted_titles[:group_max_count]
  595. # 优先使用 display_name,否则使用 group_key
  596. display_word = group_key_to_display_name.get(group_key) or group_key
  597. stats.append({
  598. "word": display_word,
  599. "count": data["count"],
  600. "position": group_key_to_position.get(group_key, 999),
  601. "titles": sorted_titles,
  602. "percentage": round(data["count"] / total_items * 100, 2) if total_items > 0 else 0,
  603. })
  604. # 排序
  605. if sort_by_position_first:
  606. stats.sort(key=lambda x: (x["position"], -x["count"]))
  607. else:
  608. stats.sort(key=lambda x: (-x["count"], x["position"]))
  609. matched_count = sum(stat["count"] for stat in stats)
  610. if not quiet:
  611. print(f"[RSS] 关键词分组统计:{matched_count}/{total_items} 条匹配")
  612. return stats, total_items
  613. def convert_keyword_stats_to_platform_stats(
  614. keyword_stats: List[Dict],
  615. weight_config: Dict,
  616. rank_threshold: int = 5,
  617. ) -> List[Dict]:
  618. """
  619. 将按关键词分组的统计数据转换为按平台分组的统计数据
  620. Args:
  621. keyword_stats: 原始按关键词分组的统计数据
  622. weight_config: 权重配置
  623. rank_threshold: 排名阈值
  624. Returns:
  625. 按平台分组的统计数据,格式与原 stats 一致
  626. """
  627. # 1. 收集所有新闻,按平台分组
  628. platform_map: Dict[str, List[Dict]] = {}
  629. for stat in keyword_stats:
  630. keyword = stat["word"]
  631. for title_data in stat["titles"]:
  632. source_name = title_data["source_name"]
  633. if source_name not in platform_map:
  634. platform_map[source_name] = []
  635. # 复制 title_data 并添加匹配的关键词
  636. title_with_keyword = title_data.copy()
  637. title_with_keyword["matched_keyword"] = keyword
  638. platform_map[source_name].append(title_with_keyword)
  639. # 2. 去重(同一平台下相同标题只保留一条,保留第一个匹配的关键词)
  640. for source_name, titles in platform_map.items():
  641. seen_titles: Dict[str, bool] = {}
  642. unique_titles = []
  643. for title_data in titles:
  644. title_text = title_data["title"]
  645. if title_text not in seen_titles:
  646. seen_titles[title_text] = True
  647. unique_titles.append(title_data)
  648. platform_map[source_name] = unique_titles
  649. # 3. 按权重排序每个平台内的新闻
  650. for source_name, titles in platform_map.items():
  651. platform_map[source_name] = sorted(
  652. titles,
  653. key=lambda x: (
  654. -calculate_news_weight(x, rank_threshold, weight_config),
  655. min(x["ranks"]) if x["ranks"] else 999,
  656. -x["count"],
  657. ),
  658. )
  659. # 4. 构建平台统计结果
  660. platform_stats = []
  661. for source_name, titles in platform_map.items():
  662. platform_stats.append({
  663. "word": source_name, # 平台名作为分组标识
  664. "count": len(titles),
  665. "titles": titles,
  666. "percentage": 0, # 可后续计算
  667. })
  668. # 5. 按新闻条数排序平台
  669. platform_stats.sort(key=lambda x: -x["count"])
  670. return platform_stats