该词典如何获取数据?

时间:2019-11-25 16:42:47

标签: python list dictionary for-loop if-statement

有人可以向我解释一下吗?此函数获取一个字符串并计算每个单词的出现频率,然后返回带有单词频率的字典。我不明白字典是如何获取数据的。

def count_words(text):
    text = text.split()
    words = {}
    for i in text:
        if i in words:
            words[i] += 1
        else:
            words[i] = 1
    return words

2 个答案:

答案 0 :(得分:2)

有评论:

def count_words(text):
    # Split the text up into words
    text = text.split()

    # Initialise an empty dictionary
    words = {}

    # For each word in the text
    for i in text:
        # If we already have the word in our dictionary, add 1 to the counter
        if i in words:
            words[i] += 1
        # Otherwise, add the word to our dictionary with the counter 1
        else:
            words[i] = 1
    # Return the dictionary of words and counts
    return words

答案 1 :(得分:1)

数据来自自变量文本。

def count_words(text):
    text = text.split()
    words = {}
    for i in text:
        if i in words:
            words[i] += 1
        else:
            words[i] = 1
    return words

因此,当您执行count_words("Hello World")时,您正在为text argument分配“ Hello World”,即成为数据。

另一种方法是在将数据传递给函数调用之前将其分配给变量:

text = "Hello World"  # This is the data
count_words(text)