frequency.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. # coding=utf-8
  2. """
  3. 频率词配置加载模块
  4. 负责从配置文件加载频率词规则,支持:
  5. - 普通词组
  6. - 必须词(+前缀)
  7. - 过滤词(!前缀)
  8. - 全局过滤词([GLOBAL_FILTER] 区域)
  9. - 最大显示数量(@前缀)
  10. - 正则表达式(/pattern/ 语法)
  11. - 显示名称(=> 别名 语法)
  12. - 组别名([组别名] 语法,作为词组第一行)
  13. """
  14. import os
  15. import re
  16. from pathlib import Path
  17. from typing import Dict, List, Tuple, Optional, Union
  18. def _parse_word(word: str) -> Dict:
  19. """
  20. 解析单个词,识别是否为正则表达式,支持显示名称
  21. 语法:
  22. - 普通词:word
  23. - 正则表达式:/pattern/ 或 /pattern/i(flags 会被忽略,默认已启用忽略大小写)
  24. - 带显示名称:word => 显示名称 或 word=>显示名称(=>两边空格可选)
  25. - 正则带显示名称:/pattern/ => 显示名称
  26. Args:
  27. word: 原始词
  28. Returns:
  29. {"word": str, "is_regex": bool, "pattern": Optional[re.Pattern], "display_name": Optional[str]}
  30. """
  31. display_name = None
  32. # 解析 => 显示名称 语法(支持 => 两边有或没有空格)
  33. # 使用正则匹配:空格可选的 =>
  34. display_match = re.search(r'\s*=>\s*', word)
  35. if display_match:
  36. parts = re.split(r'\s*=>\s*', word, 1)
  37. word = parts[0].strip()
  38. display_name = parts[1].strip() if len(parts) > 1 and parts[1].strip() else None
  39. # 解析正则表达式:支持 /pattern/ 或 /pattern/flags(如 /pattern/i)
  40. # flags 会被忽略,因为默认已启用 IGNORECASE
  41. regex_match = re.match(r'^/(.+)/([gimsux]*)$', word)
  42. if regex_match:
  43. pattern_str = regex_match.group(1)
  44. # flags 参数被忽略,统一使用 IGNORECASE
  45. try:
  46. pattern = re.compile(pattern_str, re.IGNORECASE)
  47. return {
  48. "word": pattern_str,
  49. "is_regex": True,
  50. "pattern": pattern,
  51. "display_name": display_name,
  52. }
  53. except re.error:
  54. # 正则表达式无效,当作普通词处理
  55. pass
  56. return {"word": word, "is_regex": False, "pattern": None, "display_name": display_name}
  57. def _word_matches(word_config: Union[str, Dict], title_lower: str) -> bool:
  58. """
  59. 检查词是否在标题中匹配
  60. Args:
  61. word_config: 词配置(字符串或字典)
  62. title_lower: 小写的标题
  63. Returns:
  64. 是否匹配
  65. """
  66. if isinstance(word_config, str):
  67. # 向后兼容:纯字符串
  68. return word_config.lower() in title_lower
  69. if word_config.get("is_regex") and word_config.get("pattern"):
  70. # 正则匹配
  71. return bool(word_config["pattern"].search(title_lower))
  72. else:
  73. # 子字符串匹配
  74. return word_config["word"].lower() in title_lower
  75. def load_frequency_words(
  76. frequency_file: Optional[str] = None,
  77. ) -> Tuple[List[Dict], List[str], List[str]]:
  78. """
  79. 加载频率词配置
  80. 配置文件格式说明:
  81. - 每个词组由空行分隔
  82. - [GLOBAL_FILTER] 区域定义全局过滤词
  83. - [WORD_GROUPS] 区域定义词组(默认)
  84. 词组语法:
  85. - 普通词:直接写入,任意匹配即可
  86. - +词:必须词,所有必须词都要匹配
  87. - !词:过滤词,匹配则排除
  88. - @数字:该词组最多显示的条数
  89. Args:
  90. frequency_file: 频率词配置文件路径,默认从环境变量 FREQUENCY_WORDS_PATH 获取或使用 config/frequency_words.txt
  91. Returns:
  92. (词组列表, 词组内过滤词, 全局过滤词)
  93. Raises:
  94. FileNotFoundError: 频率词文件不存在
  95. """
  96. if frequency_file is None:
  97. frequency_file = os.environ.get(
  98. "FREQUENCY_WORDS_PATH", "config/frequency_words.txt"
  99. )
  100. frequency_path = Path(frequency_file)
  101. if not frequency_path.exists():
  102. raise FileNotFoundError(f"频率词文件 {frequency_file} 不存在")
  103. with open(frequency_path, "r", encoding="utf-8") as f:
  104. content = f.read()
  105. word_groups = [group.strip() for group in content.split("\n\n") if group.strip()]
  106. processed_groups = []
  107. filter_words = []
  108. global_filters = []
  109. # 默认区域(向后兼容)
  110. current_section = "WORD_GROUPS"
  111. for group in word_groups:
  112. # 过滤空行和注释行(# 开头)
  113. lines = [line.strip() for line in group.split("\n") if line.strip() and not line.strip().startswith("#")]
  114. if not lines:
  115. continue
  116. # 检查是否为区域标记
  117. if lines[0].startswith("[") and lines[0].endswith("]"):
  118. section_name = lines[0][1:-1].upper()
  119. if section_name in ("GLOBAL_FILTER", "WORD_GROUPS"):
  120. current_section = section_name
  121. lines = lines[1:] # 移除标记行
  122. # 处理全局过滤区域
  123. if current_section == "GLOBAL_FILTER":
  124. # 直接添加所有非空行到全局过滤列表
  125. for line in lines:
  126. # 忽略特殊语法前缀,只提取纯文本
  127. if line.startswith(("!", "+", "@")):
  128. continue # 全局过滤区不支持特殊语法
  129. if line:
  130. global_filters.append(line)
  131. continue
  132. # 处理词组区域
  133. words = lines
  134. group_alias = None # 组别名([别名] 语法)
  135. # 检查第一行是否为组别名(非区域标记)
  136. if words and words[0].startswith("[") and words[0].endswith("]"):
  137. potential_alias = words[0][1:-1].strip()
  138. # 排除区域标记(GLOBAL_FILTER, WORD_GROUPS)
  139. if potential_alias.upper() not in ("GLOBAL_FILTER", "WORD_GROUPS"):
  140. group_alias = potential_alias
  141. words = words[1:] # 移除组别名行
  142. group_required_words = []
  143. group_normal_words = []
  144. group_filter_words = []
  145. group_max_count = 0 # 默认不限制
  146. for word in words:
  147. if word.startswith("@"):
  148. # 解析最大显示数量(只接受正整数)
  149. try:
  150. count = int(word[1:])
  151. if count > 0:
  152. group_max_count = count
  153. except (ValueError, IndexError):
  154. pass # 忽略无效的@数字格式
  155. elif word.startswith("!"):
  156. # 过滤词(支持正则语法)
  157. filter_word = word[1:]
  158. parsed = _parse_word(filter_word)
  159. filter_words.append(parsed)
  160. group_filter_words.append(parsed)
  161. elif word.startswith("+"):
  162. # 必须词(支持正则语法)
  163. req_word = word[1:]
  164. group_required_words.append(_parse_word(req_word))
  165. else:
  166. # 普通词(支持正则语法)
  167. group_normal_words.append(_parse_word(word))
  168. if group_required_words or group_normal_words:
  169. if group_normal_words:
  170. group_key = " ".join(w["word"] for w in group_normal_words)
  171. else:
  172. group_key = " ".join(w["word"] for w in group_required_words)
  173. # 生成显示名称
  174. # 优先级:组别名 > 行别名拼接 > 关键词拼接
  175. if group_alias:
  176. # 有组别名,直接使用
  177. display_name = group_alias
  178. else:
  179. # 没有组别名,拼接每行的显示名(行别名或关键词本身)
  180. all_words = group_normal_words + group_required_words
  181. display_parts = []
  182. for w in all_words:
  183. # 优先使用行别名,否则使用关键词本身
  184. part = w.get("display_name") or w["word"]
  185. display_parts.append(part)
  186. # 用 " / " 拼接多个词
  187. display_name = " / ".join(display_parts) if display_parts else None
  188. processed_groups.append(
  189. {
  190. "required": group_required_words,
  191. "normal": group_normal_words,
  192. "group_key": group_key,
  193. "display_name": display_name, # 可能为 None
  194. "max_count": group_max_count,
  195. }
  196. )
  197. return processed_groups, filter_words, global_filters
  198. def matches_word_groups(
  199. title: str,
  200. word_groups: List[Dict],
  201. filter_words: List,
  202. global_filters: Optional[List[str]] = None
  203. ) -> bool:
  204. """
  205. 检查标题是否匹配词组规则
  206. Args:
  207. title: 标题文本
  208. word_groups: 词组列表
  209. filter_words: 过滤词列表(可以是字符串列表或字典列表)
  210. global_filters: 全局过滤词列表
  211. Returns:
  212. 是否匹配
  213. """
  214. # 防御性类型检查:确保 title 是有效字符串
  215. if not isinstance(title, str):
  216. title = str(title) if title is not None else ""
  217. if not title.strip():
  218. return False
  219. title_lower = title.lower()
  220. # 全局过滤检查(优先级最高)
  221. if global_filters:
  222. if any(global_word.lower() in title_lower for global_word in global_filters):
  223. return False
  224. # 如果没有配置词组,则匹配所有标题(支持显示全部新闻)
  225. if not word_groups:
  226. return True
  227. # 过滤词检查(兼容新旧格式)
  228. for filter_item in filter_words:
  229. if _word_matches(filter_item, title_lower):
  230. return False
  231. # 词组匹配检查
  232. for group in word_groups:
  233. required_words = group["required"]
  234. normal_words = group["normal"]
  235. # 必须词检查
  236. if required_words:
  237. all_required_present = all(
  238. _word_matches(req_item, title_lower) for req_item in required_words
  239. )
  240. if not all_required_present:
  241. continue
  242. # 普通词检查
  243. if normal_words:
  244. any_normal_present = any(
  245. _word_matches(normal_item, title_lower) for normal_item in normal_words
  246. )
  247. if not any_normal_present:
  248. continue
  249. return True
  250. return False