编写一个Python程序,使用字典来计算字符串中的单词,并附带实际示例。
使用字典统计字符串单词的Python程序示例
在此 Python程序中,我们使用 split函数 来分割字符串。接下来,我们使用for循环来 计算 字符串中的单词。然后,我们使用 Python 的dict函数将这些单词和值转换为 字典。
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
这段使用字典统计字符串单词的代码是另一种(使用for循环)统计字符串单词的方法。在这里,我们使用 for循环 来迭代单词。
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}