【问题标题】:Finding string index in .txt file在 .txt 文件中查找字符串索引
【发布时间】:2018-10-26 23:12:39
【问题描述】:
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'

【问题讨论】:

  • word.index(" ") 将会崩溃,因为wordstr.split() 的输出:它不能包含空格。
  • @Jean-FrançoisFabre 谢谢,我知道。我删除了这些括号内的内容,因为它仍然无法正常工作。原来是 word.index(word) 但我的输出还是 0。有什么建议吗?

标签: python python-2.7 indexing


【解决方案1】:

在遍历文件时使用枚举。

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}')

【讨论】:

  • 工作就像一个魅力。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 2014-05-16
  • 2020-10-24
  • 2016-02-15
相关资源
最近更新 更多