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程序:使用字典计数字符串中单词
标题网址:http://www.shufengxianlan.com/qtweb/news39/445039.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联