该这么按字母顺序输出字符串中包含的所有单词的列表,而且列表中的每个单词与该单词出现的次数匹配?求帮助
比如输入This world is so beautiful and so wonderful.
输出:
and 1
beautiful 1
is 1
so 2
this 1
world 1
wonderful1
输入字符串后,按空格分割成列表,再遍历遍历计算字符串出现次数,结果保存到键值对中。这个输入的字符串中是否存在非字母的其他字符,如单引号或逗号,句号,如果有的话,还需要增加处理这些字符的代码。
代码如下:
参考链接:
s=input("请输入一个字符串:")
# https://blog.csdn.net/Thewei666/article/details/124406383
s=s.lower() # 根据题目例子,输出均为小写,这里先将字符串全部转为小写
# This world is so beautiful and so wonderful
# 按空格将字符串分割成列表,如果存在其他非字母字母,还需要增加处理其他字符的代码
words=s.split(" ")
#print(words)
result = {} # 保存单词及其出现次数的键值对
for w in words: # 遍历单词列表
if w in result: # 如果当前单词存在结果中,则将其出现次数+1
result[w]=result[w]+1
else: # 如果当前单词未出现在结果中,则将其次数设置为1
result[w]=1
# https://blog.csdn.net/chaojishuike/article/details/124049419
# http://www.360doc.com/content/20/1016/18/9422167_940808324.shtml
# 按字母顺序排列结果的键,并将结果保存到rkeys中
rkeys = sorted(result.keys())
# https://www.zhihu.com/question/591885267/answer/2963333897
# 遍历按字母顺序排序的键的列表,并取出结果中对应的值
for key in rkeys:
print(key,result[key])
具体该怎么写,没头绪