标签计数器Python

2024-05-12 10:59:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

分析此列表后,函数应返回:

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

只有字母和数字是允许的,其他任何东西,如空格和句点,结束标签。你知道吗

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

标签是特定于大小写的。#ZURICH应计为与#zurich不同的hashtag。你知道吗


我有一个难看的函数初稿,如果一个字符串中有多个hashtag,它就不起作用,因为它会跳过第二个。我不一定需要关于如何简化函数或使其更具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))


任何帮助都将不胜感激!你知道吗


Tags: 函数字符串in列表stringtagcounterpost
3条回答

基本上,您的函数不起作用,因为这行

hash_index = post_string.find(char)

将始终在字符串中找到第一个哈希标记的索引。这可以通过提供start index to ^{}来解决,或者更好的方法是,完全不调用str.find,而是在遍历字符串时维护索引(可以使用enumerate)。更好的是,不要使用索引,如果您将解析器重组为使用状态机,则不需要索引。你知道吗

也就是说,Pythonic实现将用regular expression替换整个函数,这将使它变得更短、更正确、更可读,而且可能更高效。你知道吗

这应该起作用:

import string
alpha = string.ascii_letters + string.digits

def analyze(posts):
    hashtag_dict = {}

    for post in posts:
        for i in post.split():
            if i[0] == '#':
                current_hashtag = sanitize(i[1:])

                if len(current_hashtag) > 0:
                    if current_hashtag in hashtag_dict:
                        hashtag_dict[current_hashtag] += 1
                    else:
                        hashtag_dict[current_hashtag] = 1

    return hashtag_dict


def sanitize(s):
    s2 = ''
    for i in s:
        if i in alpha:
            s2 += i
        else:
            break
    return s2


posts = [
        "hi #weekend",
        "good morning #zurich #limmat",
        "spend my #weekend in #zurich",
        "#zurich <3",
        "#lindehof4Ever(lol)"
        ]

print(analyze(posts))

这个任务可以用regex完成,不要害怕使用它们;) 一些快速的解决方案。你知道吗

#!/usr/bin/python3.4
import re

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

container = {}
for post in posts:
    elements = re.findall('#(\w+)', post)
    for element in elements:
        if container.get(element, None):
            container[element] += 1
        else:
            container[element] = 1
print(container)

结果:

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

相关问题 更多 >