首页 > 编程知识 正文

Python 程序:使用字典计数字符串中单词

时间:2023-11-25 09:12:53 阅读:308954 作者:AIQN

写一个 Python 程序,用字典计算字符串中的单词,并给出一个实例。

使用字典对字符串中的单词进行计数的 Python 程序示例 1

在这个 python 程序中,我们使用了一个分裂函数来分裂字符串。接下来,我们使用 for 循环来对字符串中的字进行计数。然后我们使用 Python 字典函数将这些单词和值转换成字典。

# Python Program to Count words in a String using Dictionary

string = input("Please enter any String : ")
words = []

words = string.split()
frequency = [words.count(i) for i in words]

myDict = dict(zip(words, frequency))
print("Dictionary Items  :  ",  myDict)

使用字典返回字符串的 Python 程序示例 2

这个使用字典计算字符串单词的 Python 代码是另一种计算字符串单词的方法。这里,我们使用进行循环来迭代单词。

# Python Program to Count words in a String using Dictionary

string = input("Please enter any String : ")
words = []

words = string.split() # or string.lower().split()
myDict = {}
for key in words:
    myDict[key] = words.count(key)

print("Dictionary Items  :  ",  myDict)

使用字典输出对字符串中的单词进行计数

Please enter any String : python tutorial at tutorial gateway web
Dictionary Items  :   {'python': 1, 'tutorial': 2, 'at': 1, 'gateway': 1, 'web': 1}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。