analyzer.py 28 KB

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