def wordCount(inPath):
inFile = open(inPath, 'r')
lineList = inFile.readlines()
counter = {}
for line in range(len(lineList)):
currentLine = lineList[line].rstrip("\n")
for letter in range(len(currentLine)):
if currentLine[letter] in counter:
counter[currentLine[letter]] += 1
else:
counter[currentLine[letter]] = 1
sorted(counter.keys(), key=lambda counter: counter[0])
for letter in counter:
print('{:3}{}'.format(letter, counter[letter]))
inPath = "file.txt"
wordCount(inPath)
这是输出:
^{pr2}$这是我想要的输出:
12
A 1
H 1
T 1
a 1
c 2
d 1
e 10
f 2
h 5
i 6
k 1
l 2
n 5
o 3
r 4
s 5
t 5
u 1
x 1
如何按字母顺序对“计数器”排序? 我尝试过简单地按键和值排序,但它没有按字母顺序从大写字母开始返回 谢谢你的帮助!在
单独做什么都不做:它返回一个根本不使用的结果(除非您使用
_
调用它,但这是一个命令行实践)与使用
^{pr2}$list
和.sort()
方法所能做的不同,您不能“就地”排序字典键。但您可以在键的排序版本上迭代:, key=lambda counter: counter[0]
在这里没用:你的钥匙里只有字母。撇开这一点,你可以用简化的代码来计算整个字母。
结果(包括空格字符):
相关问题 更多 >
编程相关推荐