简体   繁体   English

将数字转换为字母中的相应字母-Python 2.7

[英]Convert a number into its respective letter in the alphabet - Python 2.7

I am currently working on a python project to take a string of text, encrypt the text by adding a keyword to it and then outputting the result. 我目前正在研究一个python项目,以获取文本字符串,通过向其添加关键字来加密文本,然后输出结果。 I currently have all the features of this program operational except converting the numerical value back into text. 除了将数值转换回文本外,我目前具有该程序的所有功能。

For example, the raw text will be converted into a numerical value, for instance [a, b, c] will become [1, 2, 3] . 例如,原始文本将被转换为数值,例如[a, b, c]将变为[1, 2, 3]

Currently I have no ideas of how to correct this issue and would welcome any help, my current code is as follows: 目前,我不知道如何解决此问题,欢迎您提供任何帮助,我当前的代码如下:

def encryption():
    print("You have chosen Encryption")
    outputkeyword = []
    output = []

    input = raw_input('Enter Text: ')
    input = input.lower()

    for character in input:
        number = ord(character) - 96
        output.append(number)

    input = raw_input('Enter Keyword: ')
    input = input.lower()
    for characterkeyword in input:
        numberkeyword = ord(characterkeyword) - 96
        outputkeyword.append(numberkeyword)
        first = output
        second = outputkeyword

    print("The following is for debugging only")
    print output
    print outputkeyword

    outputfinal = [x + y for x, y in zip(first, second)]
    print outputfinal

def decryption():
    print("You have chosen Decryption")
    outputkeyword = []
    output = []
    input = raw_input('Enter Text: ')
    input = input.lower()
    for character in input:
        number = ord(character) - 96
        output.append(number)

    input = raw_input('Enter Keyword: ')
    input = input.lower()
    for characterkeyword in input:
        numberkeyword = ord(characterkeyword) - 96
        outputkeyword.append(numberkeyword)
        first = output
        second = outputkeyword

    print("The following is for debuging only")
    print output
    print outputkeyword

    outputfinal = [y - x for x, y in zip(second, first)]
    print outputfinal

mode = raw_input("Encrypt 'e' or Decrypt 'd' ")

if mode == "e":
    encryption()
elif mode == "d":
    decryption()
else:
    print("Enter a valid option")
    mode = raw_input("Encrypt 'e' or Decrypt 'd' ")

    if mode == "e":
        encryption()
    elif mode == "d":
        decryption()

Suppose you've got a list of numbers like a = [1, 2, 3] and an alphabet: alpha = "abcdef" . 假设您有一个数字列表,例如a = [1, 2, 3]和一个字母: alpha = "abcdef" Then you convert this as follows: 然后,将其转换如下:

def NumToStr(numbers, alpha):
    ret = ""
    for num in numbers:
        try:
            ret += alpha[num-1]
        except:
            # handle error
            pass
    return ret

Going by your question , you want to convert number back to text. 按照您的问题,您想要将数字转换回文本。

You can have two list declared for both the number and alphabet, such as: 您可以为数字和字母声明两个列表,例如:

num=[1,2,3....26] num = [1,2,3 .... 26]

alpa=['a','b','c'....'z'] alpa = ['a','b','c'....'z']

and after that find the index/position from the num list and find the alphabet for that index in alpa list. 然后从num列表中找到索引/位置,并在alpa列表中找到该索引的字母。

Although Your Question is not quite clear I wrote a script which do encryption using Dictionary 尽管您的问题不太清楚,但我编写了一个脚本,该脚本使用Dictionary进行加密

plaintext = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') #Alphabet String for Input
Etext = list('1A2B3C4D5E6F7G8H90IJKLMNOP') """Here is string combination of numbers and alphabets you can replace it with any kinda format and your dictionary will be build with respect to the alphabet sting"""              

def messageEnc(text,plain, encryp):
  dictionary = dict(zip(plain, encryp))
  newmessage = ''
  for char in text:
    try:
        newmessage = newmessage + dictionary[char.upper()]
    except:
        newmessage += ''
 print(text,'has been encryptd to:',newmessage)

def messageDec(text,encryp, plain):
 dictionary = dict(zip(encryp,plain))
 newmessage = ''
 for char in text:
    try:

        newmessage = newmessage + dictionary[char.upper()]

    except:
        newmessage += ''
 print(text,'has been Decrypted to:',newmessage)


while True:
 print("""
   Simple Dictionary Encryption :
   Press 1 to Encrypt
   Press 2 to Decrypt
   """)
  try:
     choose = int(input())
  except:
     print("Press Either 1 or 2")
     continue

  if choose == 1:

    text = str(input("enter something: "))
    messageEnc(text,plaintext,Etext)
    continue
  else:
    text = str(input("enter something: "))
    messageDec(text,Etext,plaintext)

A couple of things. 有几件事。 The first is to convert the coded values back to characters you can use the chr(i) command. 第一种是将编码值转换回可以使用chr(i)命令的字符。 Just remember to ad the 96 back on. 只要记得放回96。

for code in outputfinal:
        print chr(code + 96),

I tried 'aaa' as my plaintext and 'bbb' as my keyword and this printed 'ccc' which is what I think you are trying to do. 我尝试使用“ aaa”作为我的纯文本,使用“ bbb”作为我的关键字,并打印了“ ccc”,这是我认为您要尝试的做法。

Another thing. 另一件事。 The zip command iterates over two lists but (in my playing) only until one of the lists runs out of members. zip命令遍历两个列表,但是(在我的演奏中)仅直到其中一个列表成员用完为止。 If your plaintext is 10 characters and your keyword is only 5 then only the first 5 characters of your plaintext get encrypted. 如果您的纯文本为10个字符,而关键字只有5个,则仅加密您的纯文本的前5个字符。 You will need to expand or inflate your key to the length of your plaintext message. 您需要将密钥扩展或增加至纯文本消息的长度。 I played with something like this: 我玩过这样的游戏:

plaintext = ['h','e','l','l','o',' ','w','o','r','l','d']
keyword = ['f','r','e','d']

index = len(keyword) # point to the end of the key word
keyLength = len(keyword)
while index < len(plaintext): # while there are still letters in the plain text
    keyword.append(keyword[index - keyLength]) # expand the key
    index += 1

print keyword

for a,b in zip(plaintext, keyword):
    print a, b

I hope this helps. 我希望这有帮助。 Please let me know if I have misunderstood. 如果我误会了,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM