首页 > 解决方案 > 在 .txt 文件中查找字符串索引

问题描述

import crypt
import os
import shutil

'''curDir = os.getcwd()
print(curDir)
os.mkdir('NixFiles')'''

'''shutil.move("/Users/Ayounes/Desktop/Python_dev/dictionary.txt", 
"/Users/Ayounes/Desktop/Python_dev/")
shutil.move("/Users/Ayounes/Desktop/Python_dev/passwords.txt", "/Users/Ayounes/Desktop/Python_dev/")'''

def testPass(cryptPass):
salt = cryptPass[0:2]
dictFile = open('dictionary.txt', 'r')
for word in dictFile.read().split():
    #print(word)
    cryptWord = crypt.crypt(word, salt)
    #print(cryptWord)
    if(cryptWord == cryptPass):
        print('Found password: %s' % word)
        print('Index located at position: %d' % word.index(" "))
        return
print('Password was not found.\n')
return

def main():
    passFile = open('passwords.txt','r')
    cryptPass1 = passFile.readline()
    testPass(cryptPass1)


if __name__ == '__main__':
    main()

我的程序从 passwords.txt 文件中检索哈希。然后它继续获取 salt 参数(哈希的前 2 个字符),并逐行对 dictionary.txt 文件中的单词进行哈希处理,同时将该哈希值与 passwords.txt 文件中的原始哈希值进行比较。

一旦我们找到匹配项,它就会假定打印出哪个密码是原始哈希的解密匹配项。

'grilledcheese22' 是 dictionary.txt 文件中位置 3 的第 4 个单词,它一直在位置输出索引:0

如何在 .txt 文件中输出正确的位置?

原始哈希:22CWIxwLb7tWM

dictionary.txt 中的解密哈希:'grilledcheese22'

标签: pythonpython-2.7indexing

解决方案


在遍历文件时使用 enumerate。

for i, word in enumerate(dictFile.read().split()):
    ...
    ...
        print('Index located at position: %d' % i)
        #print('Index located at position: {}'.format(i))
        #print(f'Index located at position: {i}')

推荐阅读