如何编写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
相关产品推荐
相关产品推荐

