用字母B中的连续字母替换姓氏中的每个字母

2024-10-02 12:36:06 发布

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

如何用字母表中的连续字母替换姓氏中的每个字母?我需要这个脚本作为掩蔽工具。在

姓氏逻辑:(a改为b,b改为c,…,z改为a)

约翰·多伊将成为约翰·埃普夫

输入文件:names.txt

John yi
kary Strong
Joe Piazza
So  man

Tags: 文件工具txt脚本names字母逻辑john
2条回答

这称为Caesar's cipher。在

看看这里是怎么做到的:https://stackoverflow.com/a/8895517/6664393

您需要对其进行一点更改,以允许使用大写字符:

def caesar(plaintext, shift):
    alphabet_lower = string.ascii_lowercase
    alphabet_upper = string.ascii_uppercase
    alphabet = alphabet_lower + alphabet_upper
    shifted_alphabet_lower = alphabet_lower[shift:] + alphabet_lower[:shift]
    shifted_alphabet_upper = alphabet_upper[shift:] + alphabet_upper[:shift]
    shifted_alphabet = shifted_alphabet_lower + shifted_alphabet_upper
    table = string.maketrans(alphabet, shifted_alphabet)
return plaintext.translate(table)

使用shift = 1来移动一。在

你的问题可以解决如下:

parts = name.split()
parts[1]=''.join([chr((ord(c) - 65 + 1) % 26 + 65)
                  if ord(c) < 91 else
                  chr((ord(c) - 97 + 1) % 26 + 97)
                  for c in parts[1]])
' '.join(parts)

在这里,我将姓氏定义为字符串的第二个单词,这当然是一个很强的假设,但改进这一点并不是问题的主要问题。在

移位字符是在列表理解中完成的,每个字符都是单独处理的,并首先使用ord转换成它的ASCII代码。大写字母的ASCII码是65-90(A-Z),小写字母的ASCII码是97-122(a-z)。因此,使用一个条件ord(c) < 91来分隔这些情况。然后,在每种情况下,ASCII码被转换成0-25范围内的值,移位(在示例中,递增1),并使用模运算% 26将移位的{}转换回a。结果值随后被转换回字母ASCII码的正确范围。在

相关问题 更多 >

    热门问题