Python中的文本移位函数

2024-09-29 02:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写代码,所以你可以把文字沿字母表移动两个位置:“ab cd”应该变成“cd ef”。我正在使用Python 2,这是我目前所得到的:

def shifttext(shift):
    input=raw_input('Input text here: ')
    data = list(input)
    for i in data:
        data[i] = chr((ord(i) + shift) % 26)
        output = ''.join(data)
    return output
shifttext(3)

我得到以下错误:

File "level1.py", line 9, in <module>
    shifttext(3)
File "level1.py", line 5, in shifttext
    data[i] = chr((ord(i) + shift) % 26)
TypError: list indices must be integers, not str

所以我得把字母改成数字?但我以为我已经做到了?


Tags: 代码inpyinputoutputdatashiftline
3条回答

马蒂金的回答很好。这里有另一种实现相同目标的方法:

import string

def shifttext(text, shift):
    shift %= 26 # optional, allows for |shift| > 26 
    alphabet = string.lowercase # 'abcdefghijklmnopqrstuvwxyz' (note: for Python 3, use string.ascii_lowercase instead)
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    return string.translate(text, string.maketrans(alphabet, shifted_alphabet))

print shifttext(raw_input('Input text here: '), 3)

您在字符列表上循环,因此i是一个字符。然后尝试使用i字符作为索引将其存储回data。那不行。

使用enumerate()获取索引值:

def shifttext(shift):
    input=raw_input('Input text here: ')
    data = list(input)
    for i, char in enumerate(data):
        data[i] = chr((ord(char) + shift) % 26)
    output = ''.join(data)
    return output

可以使用生成器表达式简化此过程:

def shifttext(shift):
    input=raw_input('Input text here: ')
    return ''.join(chr((ord(char) + shift) % 26) for char in input)

但是现在你会注意到你的% 26不起作用;ASCII代码点在26之后开始

>>> ord('a')
97

您需要使用ord('a')值来代替使用模数;减法将您的值置于0-25的范围内,然后再添加:

    a = ord('a')
    return ''.join(chr((ord(char) - a + shift) % 26) + a) for char in input)

但这只适用于小写字母;这可能很好,但您可以通过将输入小写来强制:

    a = ord('a')
    return ''.join(chr((ord(char) - a + shift) % 26 + a) for char in input.lower())

如果我们从函数中请求输入,将其集中在做好一项工作上,这将变成:

def shifttext(text, shift):
    a = ord('a')
    return ''.join(chr((ord(char) - a + shift) % 26 + a) for char in text.lower())

print shifttext(raw_input('Input text here: '), 3)

在交互提示下使用这个,我看到:

>>> print shifttext(raw_input('Input text here: '), 3)
Input text here: Cesarsalad!
fhvduvdodgr

当然,现在标点符号也被采用了。上一次修订,现在只更改字母:

def shifttext(text, shift):
    a = ord('a')
    return ''.join(
        chr((ord(char) - a + shift) % 26 + a) if 'a' <= char <= 'z' else char
        for char in text.lower())

我们得到:

>>> print shifttext(raw_input('Input text here: '), 3)
Input text here: Ceasarsalad!
fhdvduvdodg!

看来你在做塞萨尔密码加密,所以你可以试试这样的方法:

strs = 'abcdefghijklmnopqrstuvwxyz'      #use a string like this, instead of ord() 
def shifttext(shift):
    inp = raw_input('Input text here: ')
    data = []
    for i in inp:                     #iterate over the text not some list
        if i.strip() and i in strs:                 # if the char is not a space ""  
            data.append(strs[(strs.index(i) + shift) % 26])    
        else:
            data.append(i)           #if space the simply append it to data
    output = ''.join(data)
    return output

输出:

In [2]: shifttext(3)
Input text here: how are you?
Out[2]: 'krz duh brx?'

In [3]: shifttext(3)
Input text here: Fine.
Out[3]: 'Flqh.'

strs[(strs.index(i) + shift) % 26]:上面的行表示在strs中找到字符i的索引,然后向其添加移位值。现在,在最终值(index+shift)上应用%26来获取移位索引。当传递到strs[new_index]时,这个移位索引产生所需的移位字符。

相关问题 更多 >