首页 > 解决方案 > 如何在 python 中查找文本文件的 ASCII 值?

问题描述

我想在 python 中输入一个文本文件,我希望 python 读取该文件并找到每个字符的 ASCII 值以及空格和所有数值。到目前为止我所尝试的是这个。

d={}
f = open("MyFile.txt","r")
input_message= f.read()
for i in range(len(input_message)):
    d[i]=0
    for it in input_message[i]:
        d[i]=ord(it)
public key = (3163, 103603)
def encrypt(d,public_key):
    key,n = public_key
    ctext = [pow(char,key,n) for char in d]
    return ctext
end_encrypt = time.time_ns()

这给出了一个错误。

TypeError                                 Traceback (most recent call last)
<ipython-input-4-b7d0a6bd3c5e> in <module>
    104     #input_message = input("Enter the message = ")
    105 
--> 106     ctext = encrypt(input_message,public_key)
    107     print("encrypted:",ctext)
    108     plaintext = decrypt(ctext, private_key)

<ipython-input-4-b7d0a6bd3c5e> in encrypt(d, public_key)
     82 def encrypt(d,public_key):
     83     key,n = public_key
---> 84     ctext = [pow(char,key,n) for char in d]
     85     return ctext
     86 end_encrypt = time.time_ns()

<ipython-input-4-b7d0a6bd3c5e> in <listcomp>(.0)
     82 def encrypt(d,public_key):
     83     key,n = public_key
---> 84     ctext = [pow(char,key,n) for char in d]
     85     return ctext
     86 end_encrypt = time.time_ns()

TypeError: unsupported operand type(s) for pow(): 'str', 'int', 'int'

目前我正在使用 jupyter 笔记本。我不确定我错在哪里。

标签: pythonencryptionjupyter-notebookascii

解决方案


将其作为二进制文件读取。然后你得到一串字节,不需要转换:

def encrypt(d,public_key):
    key,n = public_key
    ctext = [pow(char,key,n) for char in d]
    return ctext

d = open("x.py","rb").read()
public_key = (3163, 103603)
print(encrypt( d, public_key ))

推荐阅读