我无法看到此代码无法正常工作。你能帮忙吗?
到目前为止,这是我的代码:
import math
while True:
message = input("Enter a message :")
code1 = input("Enter a first code word :")
code2 = input("Enter a second code word :")
newmessage = ""
new = ""
listM = [(ord(m.lower())- 96) for m in message]
listC1 = [(ord(c1.lower())- 96) for c1 in code1]
listC2 = [(ord(c2.lower())- 96) for c2 in code2]
messagec1 = math.ceil(len(listM) / len(listC1))
messagec2 = math.ceil(len(listM) / len(listC2))
newlistC1 = listC1 * messagec1
newlistC2 = listC2 * messagec2
adding1 = [listM[i] + newlistC1[i] for i in range(0,len(listM))]
adding2 = [adding1[i] + newlistC2[i] for i in range(0,len(adding1))]
finallist = [(adding2[i] + 96) for i in range(0,len(adding2))]
for i in range(0,len(finallist)):
newmessage += chr(finallist[i])
print("In the text file called message")
textfile = open("message.txt","w")
textfile.write(newmessage)
textfile.close()
choice = input("would you like to decrypt aswell? (if you do type yes)")
if choice == "yes":
textfile = open("message.txt","r")
textfileM = textfile.readlines()
textfile.close
listM = [(ord(str(m))- 96) for m in textfileM]
taking1 = [listM[i] - newlistC2[i] for i in range(0,len(listM))]
taking2 = [taking1[i] - newlistC1[i] for i in range(0,len(listM))]
decryption = [(taking2[i] + 96) for i in range(0,len(taking2))]
for i in range(0,len(decryption)):
new += chr(decryption[i])
print(new)
当我运行此代码时,它会输出:
Enter a message :hello
Enter a first code word :hi
Enter a second code word :cow
In the text file called message
Traceback (most recent call last):
File "C:\Users\User\Desktop\python\TASK £ TEXT FILES TEST.py", line 22, in <module>
textfile.write(newmessage)
File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\x8b' in position 2: character maps to <undefined>
答案 0 :(得分:-1)
尝试使用编解码器库并使用它打开文件。它应该工作。
import codecs
f = codecs.open(filename, 'w', 'utf-8')
f.write(your_data)
您也可以将其设置为&#34; global&#34;该模块的配置:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
然后在阅读时阅读文件。
我还建议您阅读这篇文章:http://www.joelonsoftware.com/articles/Unicode.html