analyzer.py 28 KB

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