How to count the occurrence of words in a string using Python?

One way to count the frequency of words in a string is by using Python’s built-in functions and string methods.

def count_words(string):
    # 将字符串转换为小写,并去除标点符号
    string = string.lower().replace(",", "").replace(".", "").replace("!", "").replace("?", "")

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

    # 创建一个空字典来存储单词出现的次数
    word_count = {}

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

    # 返回单词出现的次数字典
    return word_count

# 测试示例
string = "I am a student. I am studying computer science."
word_count = count_words(string)
print(word_count)

The output result is:

{'i': 2, 'am': 2, 'a': 1, 'student': 1, 'studying': 1, 'computer': 1, 'science': 1}

This code first converts a string to lowercase and removes punctuation marks. Then, it splits the string into a list of words. Next, it creates an empty dictionary to store the count of each word. Then, it iterates through the list of words, counting the occurrences of each word and storing the results in the dictionary. Finally, it returns the dictionary of word counts.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds