美图齐众专注资阳网站设计 资阳网站制作 资阳网站建设
资阳网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

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

创新互联Python教程:

写一个 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}

网页题目:Python程序:使用字典计数字符串中单词
URL网址:http://www.zsjierui.cn/article/cceesei.html

其他资讯