新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Python程序:使用字典計數(shù)字符串中單詞
創(chuàng)新互聯(lián)Python教程:

寫一個 Python 程序,用字典計算字符串中的單詞,并給出一個實例。
使用字典對字符串中的單詞進(jìn)行計數(shù)的 Python 程序示例 1
在這個 python 程序中,我們使用了一個分裂函數(shù)來分裂字符串。接下來,我們使用 for 循環(huán)來對字符串中的字進(jìn)行計數(shù)。然后我們使用 Python 字典函數(shù)將這些單詞和值轉(zhuǎn)換成字典。
# 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 代碼是另一種計算字符串單詞的方法。這里,我們使用進(jìn)行循環(huán)來迭代單詞。
# 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)使用字典輸出對字符串中的單詞進(jìn)行計數(shù)
Please enter any String : python tutorial at tutorial gateway web
Dictionary Items : {'python': 1, 'tutorial': 2, 'at': 1, 'gateway': 1, 'web': 1} 標(biāo)題名稱:Python程序:使用字典計數(shù)字符串中單詞
網(wǎng)站地址:http://www.dlmjj.cn/article/cceesei.html


咨詢
建站咨詢
