Skip to main content
 首页 » 编程设计

python之标签计数器 Python

2025年05月04日15xiaohuochai

我是一名 Python 初学者。作为练习,我必须编写一个 python 函数来扫描字符串列表,计算主题标 checkout 现的次数并将其放入字典中。示例:

[ 
    "hi #weekend", 
    "good morning #zurich #limmat", 
    "spend my #weekend in #zurich", 
    "#zurich <3" 
] 

分析完这个列表后,函数应该返回:

{'weekend': 2, 'zurich': 3, 'limmat': 1}

只允许使用字母和数字,空格和句点等其他任何内容都可以作为标签的结尾。

我们可以假设该参数始终是一个有效的字符串列表,您不需要提供任何类型的输入验证。

主题标签是特定于案例的。 #ZURICH 应算作与 #zurich 不同的主题标签。


我有一个丑陋的函数初稿,如果字符串中有多个主题标签,它就不起作用,因为它会跳过第二个。我不一定需要关于如何简化函数或使其更像 pythonic 的提示(当然,它仍然会受到赞赏)。我只想知道为什么它不起作用。


def analyze(posts): 
    hashtag_dict = {} 
    for post_string in posts: 
        for char in post_string: 
            if char == "#": 
                hash_index = post_string.find(char) 
                counter = 1 
                tag = "" 
                for tag_char in post_string[hash_index + 1:]: 
                    if tag_char.isdigit() or tag_char.isalpha(): 
                        tag += tag_char 
                    elif tag in hashtag_dict: 
                        counter += 1 
                        hashtag_dict[tag] = counter 
                        break 
                    else: 
                        hashtag_dict[tag] = counter 
                        break 
    return hashtag_dict 
 
 
posts = [ 
        "hi #weekend", 
        "good morning #zurich #limmat", 
        "spend my #weekend in #zurich", 
        "#zurich <3"] 
 
print(analyze(posts)) 
 

如有任何帮助,我们将不胜感激!

请您参考如下方法:

从根本上说,你的函数不起作用,因为这一行

hash_index = post_string.find(char) 

将始终在字符串中找到第一个 哈希标签的索引。这可以通过提供 start index to str.find 来解决。 ,或者,更好的是,根本不调用 str.find 而是在遍历字符串时维护索引(您可以为此使用 enumerate)。更好的是,不要使用索引,如果您重构解析器以使用状态机,则不需要它。

也就是说,Pythonic 实现会将整个函数替换为 regular expression ,这将使它变得更短、更正确、更易读,并且可能更高效。