You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Python程序分析字符串提取统计符合规则的话题标签并存入字典

实现方案

你只需要在生成器的筛选条件里补充对应规则的判断即可,修改后的代码如下:

from collections import Counter

def analyze(posts):
    counter = Counter(
        x[1:] for x in ' '.join(posts).split() 
        if x.startswith('#') 
        and len(x) > 1  # 排除仅#的空标签
        and x[1].isalpha()  # 要求#后第一个字符是字母
    )
    return dict(counter)


posts = [
    "hi #weekend",
    "good morning #madrid #fun",
    "spend my #weekend in #madrid",
    "#madrid <3"]

print(analyze(posts))

规则适配说明

  • 补充len(x) > 1:对应规则1,过滤掉只有单个#的空标签
  • 补充x[1].isalpha():对应规则2,过滤掉#后第一位不是字母的无效标签
  • 大小写区分:原生逻辑默认区分字符串大小写,天然满足规则3的要求

内容的提问来源于stack exchange,提问作者lostw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:27:00