0

我想逐个字符比较字符串 char 的长度thisline。但是,我正在超出范围错误。是因为Index, 属于 -1 或 £#$½$#£

def vigsquare(printable=False):
    '''
    Returns a string like a vigenere square,
    printable joins each row with a newline so it's literally square
    printable=False (defaul) joins without newlines for easier 
    searching by row and column index
    '''
    alpha = string.ascii_uppercase
    rotater = collections.deque(alpha)
    vigsquare_list = []
    for i in range(26):
        vigsquare_list.append(''.join(rotater))
        rotater.rotate(-1)
    if printable:
        return '\n'.join(vigsquare_list) 
    else:
        return ''.join(vigsquare_list)

def v(row, column):
    ''' 
    Return a character from a vigenere square by 
    row and column letter.
    vigenere('L', 'G') returns 'R'
    '''
    alpha = string.ascii_uppercase
    rowindex = alpha.find(row)
    columnindex = alpha.find(column)
    return vigsquare()[rowindex*26 + columnindex]


p = "LEMON"
Kasiski = open("c:\\HobbitStory.txt","r")

lines = Kasiski.readlines()
for i in lines:
    thisline = i.split()
    Index = len(thisline)
    while (Index>=0):
        print(v(thisline[Index],p[Index]))
        Index -= 1
4

2 回答 2

4

您设置Index为线的长度;但是索引转到len() - 1,因为 Python 使用基于 0 的索引。

减1:

thisline = i.split()
Index = len(thisline) - 1
while Index >= 0:
    print(v(thisline[Index], p[Index]))
    Index -= 1

如果有超过 5 个元素,这仍然会抛出一个只有 5 个字符的元素。IndexErrorthislinep

如果你使用zip(),reversed()和一个for循环会更容易:

thisline = i.split()
for a, b in reversed(zip(thisline, p)):
    print(v(a, b))

现在保证您不会遇到索引问题。

于 2013-11-10T01:12:23.733 回答
1

不要忘记你的进口:

import string
import collections

现在我在哪里见过这段代码...... :)

于 2013-11-10T01:41:15.160 回答