Python中的文本移位功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14424500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Text Shift function in Python
提问by Ampi Severe
I'm writing code so you can shift text two places along the alphabet: 'ab cd' should become 'cd ef'. I'm using Python 2 and this is what I got so far:
我正在编写代码,以便您可以将文本沿字母表移动两个位置:'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)
I get the following error:
我收到以下错误:
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
So I have to change the letter to numbers somehow? But I thought I already did that?
所以我必须以某种方式将字母更改为数字?但我以为我已经这样做了?
采纳答案by Ashwini Chaudhary
Looks you're doing cesar-cipher encryption, so you can try something like this:
看起来你正在做 cesar-cipher 加密,所以你可以尝试这样的事情:
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
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]: line above means find the index of the character iin strsand then add the shift value to it.Now, on the final value(index+shift) apply %26 to the get the shifted index. This shifted index when passed to strs[new_index]yields the desired shifted character.
strs[(strs.index(i) + shift) % 26]:线以上手段找到字符的索引i中strs,然后添加移位值it.Now,对最终值(索引+偏移)申请%26向得到移位索引。传递给这个移位的索引时会strs[new_index]产生所需的移位字符。
回答by Colonel Panic
It's easier to write a straight function shifttext(text, shift). If you want a prompt, use Python's interactive mode python -i shift.py
直接写函数更容易shifttext(text, shift)。如果需要提示,请使用 Python 的交互模式python -i shift.py
> shifttext('hello', 2)
'jgnnq'
回答by Martijn Pieters
You are looping over the list of characters, and iis thus a character. You then try to store that back into datausing the icharacter as an index. That won't work.
您正在遍历字符列表,i因此是一个字符。然后,您尝试将其存储回data使用该i字符作为索引。那行不通。
Use enumerate()to get indexes andthe values:
使用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
You can simplify this with a generator expression:
您可以使用生成器表达式简化此操作:
def shifttext(shift):
input=raw_input('Input text here: ')
return ''.join(chr((ord(char) + shift) % 26) for char in input)
But now you'll note that your % 26won't work; the ASCII codepoints startafter 26:
但是现在你会注意到你的方法% 26行不通;ASCII 代码点在 26 之后开始:
>>> ord('a')
97
You'll need to use the ord('a')value to be able to use a modulus instead; subtracting puts your values in the range 0-25, and you add it again afterwards:
您需要使用该ord('a')值才能使用模数;减去将您的值放在 0-25 范围内,然后再添加它:
a = ord('a')
return ''.join(chr((ord(char) - a + shift) % 26) + a) for char in input)
but that will only work for lower-case letters; which might be fine, but you can force that by lowercasing the input:
但这仅适用于小写字母;这可能没问题,但您可以通过小写输入来强制这样做:
a = ord('a')
return ''.join(chr((ord(char) - a + shift) % 26 + a) for char in input.lower())
If we then move asking for the input out of the function to focus it on doing one job well, this becomes:
如果我们接着要求函数的输入以专注于做好一项工作,这将变成:
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)
and using this on the interactive prompt I see:
并在交互式提示上使用它,我看到:
>>> print shifttext(raw_input('Input text here: '), 3)
Input text here: Cesarsalad!
fhvduvdodgr
Of course, now punctuation is taken along. Last revision, now only shifting letters:
当然,现在标点符号被采用了。上次修订,现在只转换字母:
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())
and we get:
我们得到:
>>> print shifttext(raw_input('Input text here: '), 3)
Input text here: Ceasarsalad!
fhdvduvdodg!
回答by oli
Martijn's answer is great. Here is another way to achieve the same thing:
Martijn 的回答很棒。这是实现相同目的的另一种方法:
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)

