计算大量密码中的单个字符而不会杀死循环

时间:2017-11-30 20:31:43

标签: python

我正试图计算,例如,出于好奇心,大量密码列表中有多少个。但我认为当我试图为一个角色添加一个计数时,它会杀死所有角色的循环。

#Examine passwords.txt

file = open('passwords.txt','r')
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
h = 0
i = 0
j = 0
k = 0
l = 0
m = 0
n = 0
o = 0
p = 0
q = 0
r = 0
s = 0
t = 0
u = 0
v = 0
w = 0
x = 0
y = 0
z = 0

with open('passwords.txt','r') as fileobj:
    for line in fileobj:
       for char in line:
           if char == a:
               a += 1
           elif char == b:
               b += 1
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
    

2 个答案:

答案 0 :(得分:0)

您应该使用dictionary(或具有订单的list)来存储每个字母的计数。这比使用26一个字母变量更好 更糟糕!

要创建字典,您可以对文件的整个内容使用str.count的字典理解。

with open('passwords.txt','r') as fileobj:
    text = fileobj.read()
    letterCounts = {c: text.count(c) for c in "abcdefghijklmnopqrstuvwxyz"}

会给letterCounts类似的东西:

{'s': 0, 'a': 4, 'o': 0, 'i': 0, 'm': 0, 'k': 0, 'q': 0, 'y': 0, 'c': 1, 'j': 0, 'b': 4, 'g': 0, 'd': 1, 'h': 0, 'e': 0, 'f': 0, 'u': 0, 'n': 0, 'w': 0, 't': 0, 'x': 0, 'p': 0, 'l': 0, 'r': 0, 'z': 0, 'v': 0}

答案 1 :(得分:0)

from collections import Counter

with open('passwords.txt','r') as fileobj:
    counts = Counter()
    for line in fileobj:
        counts.update(line)

countsCounter跟踪文件中出现的所有字符的计数。您可以使用a

访问counts['a'] s的数量