寫一個 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}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/248270.html