【问题标题】:search in txt file python在 txt 文件中搜索 python
【发布时间】:2017-08-15 02:13:33
【问题描述】:

我已经研究这段代码好几天了,但没有结果。函数autodecrypt 接受由encrypt 加密的字符串,其域A-Z 和a-z 中的字符由数字offset 更改。因此,在 ASCII 代码中,“A”为 65,如果 offset = 7,则“A”现在为“H”(其代码 # 为 72)。将尝试 0-95 的偏移值。如果 85% 或更多的单词出现在名为dictionary.txt 的 txt 文件中,则将检查解密,该文件基本上包含一堆常用单词。这就是我的问题所在:它没有正确检查我生成的字符串是否在 txt 文件中。

def autodecrypt(ciphertext):
    text = list(ciphertext)
    t = open ('dictionary.txt', 'r')
    m = t.read()
    diccond = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ' #initializing variables
    ntext = []
    ctext = ''
    i = 0
    offset = 0
    check = 0
    while offset <= 95:                   #cycling through 95 offset values
        while i < len(text):              #decrypting ciphertext with given offset value
            r = ord(text[i])
            if r - offset < 32:
                s = chr(127 - (offset - (r - 32)))
            else:
                s = chr(r - offset)
            ntext.append(s)
            i+=1
        stext = ''.join(ntext) #make decrypted list (ntext) into string, stext
        for j in stext:       #removing punctuation and store in new string, ctext
            if j in diccond:
                ctext += j
        cltext = ctext.lower() #lowercasing ctext string
        for k in (cltext.split(' ')):  #checking if ctext, list version, is in txt file
            if k in m:
                check +=1
        if check / len(ctext.split(' ')) >= 0.85: #checking if 85% or over of ctext string version in txt file
            return stext
        else:                            #else if there is not any fail and return cipher text (see below)
            fail = 0
        check = 0 #resetting all variables 
        ctext = ''
        ntext=[]  
        i=0
        offset +=1 #increasing offset
    if fail == 0:
        return ciphertext

此外,如果没有 85% 或更多匹配,则返回原始加密字符串。

【问题讨论】:

  • 当前的问题是您在循环中(在另一个循环中)使用m = t.read(),但是在第一次迭代之后,t.read() 将返回一个空字符串。您应该在开头阅读文件并使用结果。这是最干净的方法。此外,您可能应该将字典中的单词放在set 中,这样不会很慢。
  • 是的,我在发布后对其进行了编辑,但它仍然无法正常工作。专门针对这个测试用例,原文是'Je pense, donc, je suis.',密文是'Wr-}r{!r9-q|{p9-wr-!#v!;'。原始文本中的单词不在 txt 文件中,因此它应该返回加密文本,尽管它返回 'f"&lt;-"+0"H&lt;!,+ H&lt;\'"&lt;02&amp;0J'
  • 使用密文运行代码时 = 'Wr-}r{!r9-q|{p9-wr-!#v!;'一个空的 dictionary.txt 它返回正确的结果为 'Wr-}r{!r9-q|{p9-wr-!#v!;'。一些更具体的测试数据会有所帮助。当您尝试在字典文件中查找 'je' 并且它包含一个类似 'meje' 的单词时会很受欢迎。
  • “检查不正确”是什么意思?你观察到什么行为?有例外还是只是输出不好?什么是糟糕的输出,它与您的预期有何不同?

标签: python dictionary encryption


【解决方案1】:

假设这是 Python 2.x(您需要更具体地标记!),问题似乎在这里:check / len(ctext.split(' ')) 这是一个整数除法,0 和 1 是唯一可能的结果(它只能是1 如果每个单词都在文件中)。要获得浮点结果,您需要在除法之前将至少一个操作数转换为浮点数:float(check) / len(ctext.split(' ')) 可能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    相关资源
    最近更新 更多