Python数据结构,统计输入的字符串中的单词个数

Python

使用数据结构知识,统计通过输入的字符串中的单词个数。

下面Python代码使用字符串和字典数据结构,统计通过输入的字符串中的单词个数,望采纳

def count_words(s):
    # 使用字典存储每个单词出现的次数
    word_count = {}

    # 将字符串拆分成单词列表
    words = s.split()

    # 统计每个单词出现的次数
    for word in words:
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1

    return word_count

s = "This is a test string. This string contains multiple words."
word_count = count_words(s)

# 输出每个单词出现的次数
for word, count in word_count.items():
    print("{}: {}".format(word, count))

输出结果如下:

This: 2
is: 1
a: 1
test: 1
string.: 1
string: 1
contains: 1
multiple: 1
words.: 1