但是运行起来,有时候字符串最后不以’.’结尾,会使最后一个单词无法录入,如何改进
时间: 2024-03-14 12:48:00 浏览: 19
如果输入的字符串最后不以 '.' 结尾,最后一个单词无法被正确统计的问题,可以通过添加一个额外的判断来解决。具体做法是,在遍历完所有单词后,如果最后一个单词没有被统计到,就手动将其添加到字典中。
修改后的代码如下所示:
```
import re
line = input()
words = re.split("[ ,.]", line)
d = {}
for i in range(len(words) - 1):
if len(words[i]) in d:
d[len(words[i])] += 1
else:
d[len(words[i])] = 1
# 判断最后一个单词是否被统计到
if len(words[-1]) not in d:
d[len(words[-1])] = 1
else:
d[len(words[-1])] += 1
length = 0
total = 0
for key, value in sorted(list(d.items())):
length += key * value
total += value
print("(%d,%d)" % (key, value))
print("%d/%d" % (length, total))
```
这样,无论输入的字符串最后是否以 '.' 结尾,都能够正确统计所有单词的长度出现次数。