python 生成器函数未产生输出

python generator function not yielding output

import itertools
def password_generator():
    with open("D:\Password Hacker\Password Hacker\task\passwords.txt", "r") as passfile:
        for word in passfile:
            if not word.isdigit():
                for var in itertools.product(*([letter.lower(), letter.upper()]for letter in word.strip("\n"))):
                    yield ("".join(var))
            else:
                yield (word.strip("\n"))

g = password_generator()
for i in range(10):
print(g.__next__()) #prints same result everytime...

该代码从文件 passwords.txt 中生成单词中大小写字母的所有可能组合。但是,代码在每次迭代中输出相同的结果

尝试:

import itertools


def password_generator():
    with open("D:\Password Hacker\Password Hacker\task\passwords.txt", "r") as passfile:
        for word in passfile:

            print('word : ', word , type(word), word.isdigit()) #you can comment out this line

            if not word.strip("\n").isdigit():
                for var in itertools.product(*([letter.lower(), letter.upper()]for letter in word.strip("\n"))):
                    yield ("".join(var))
            else:
                yield (word.strip("\n"))

g = password_generator()

  
try :  
    while g:
        print(g.__next__()) #prints same result everytime...
        
except:
    print('empty')

输入passwords.txt文件:

pippo
pluto
123456

输出:

word :  pippo
 <class 'str'> False
pippo
pippO
pipPo
pipPO
piPpo
piPpO
piPPo
piPPO
pIppo
pIppO
pIpPo
pIpPO
pIPpo
pIPpO
pIPPo
pIPPO
Pippo
PippO
PipPo
PipPO
PiPpo
PiPpO
PiPPo
PiPPO
PIppo
PIppO
PIpPo
PIpPO
PIPpo
PIPpO
PIPPo
PIPPO
word :  pluto
 <class 'str'> False
pluto
plutO
pluTo
pluTO
plUto
plUtO
plUTo
plUTO
pLuto
pLutO
pLuTo
pLuTO
pLUto
pLUtO
pLUTo
pLUTO
Pluto
PlutO
PluTo
PluTO
PlUto
PlUtO
PlUTo
PlUTO
PLuto
PLutO
PLuTo
PLuTO
PLUto
PLUtO
PLUTo
PLUTO
word :  123456
 <class 'str'> False
123456
empty

您可以使用以下方法获得相同的结果:

import itertools


def count_pwd():
    with open("passwords.txt", "r") as passfile:
        
        cnt = 0
        
        for word in passfile.readlines():
            
            if not word.strip("\n").isdigit():
            
                cnt += 2**len(word)
                
            else:
                
                cnt += 1


    return cnt        
        
    

def password_generator():
    with open("D:\Password Hacker\Password Hacker\task\passwords.txt", "r") as passfile:
        
        for word in passfile.readlines():
            
                
                if not word.strip("\n").isdigit():
                    for var in itertools.product(*([letter.lower(), letter.upper()]for letter in word.strip("\n"))):
                        yield ("".join(var))
                else:
                    yield (word.strip("\n"))


g = password_generator()


gg = count_pwd()

print(gg)

try: 
    for i in range(gg):
        print(g.__next__()) #prints same result everytime...
        
except:
    print('empty')

不管怎样,你得到的是你的 password.txt 文件

包含像 22B1a3

这样的密码