使用空格时出现 UnicodeEncodeError

Posted

技术标签:

【中文标题】使用空格时出现 UnicodeEncodeError【英文标题】:UnicodeEncodeError when a space is used 【发布时间】:2016-02-15 15:57:38 【问题描述】:

我创建了一个 vigenere cipher 然后进行编码和解码,但在这种情况下,编码的单词被写入文本文件,解码部分读取编码的单词并对其进行解码。问题是当我在消息或关键字中输入空格时出现错误(两者都转换为 ascii 并添加或删除)。

我找到了问题的根源[我认为]:http://imgur.com/a/6T8hf[显示问题的 2 个屏幕截图的 imgur 链接]

我将在文本文件中读取和写入编码字的部分转换为注释,并将编码字打印到外壳中,通过这样做,代码在消息和关键字中使用空格进行编码没有问题.但是,当我取消注释它们并使程序将编码的消息写入文本文件时,它会出现一个错误,提示“'charmap' 无法编码字符”。如果有人可以帮助我将不胜感激!

encode="" # encoded text is saved in this variable
decode="" # decoded text is saved in this variable
encodedTextSaved="" # what the read encoded text from the text file is saved in 
decodedText = "" # When the encoded text is read back in from the file it goes in this variable
from itertools import cycle

def encrypt(message,keyWord): #defines the variable named 'encrypt'
    def encryptLetter(letterKey):
        letter,keyWord=letterKey
        return chr(ord(letter)+ord(keyWord)) # adds the ascii value of letter and the KeyWord togther and converts them to a character 
    keySeq=cycle(keyWord)
    return "".join(map(encryptLetter,zip(message,keySeq)))

def decrypt(message,keyWord): # defines the variable named 'decrypt'
    def decryptLetter(letterKey):
        letter,keyWord=letterKey
        return chr(ord(letter)-ord(keyWord)) # takes away the the ascii value of letter and the KeyWord togther and converts them to a character 
    keySeq=cycle(keyWord)
    return "".join(map(decryptLetter,zip(message,keySeq)))

start = input("Do you want to start this ingenuitive program (y/n): ")
if start == 'y':
    print()    
    while 1==1:
        decision=input('Do you wish to Encrypt(1) or Decrypt(2) a message or Quit(3):  ')
        if decision == '1':
            while 1==1:
                text=input("Enter text message to encode: ")
                if text == '':
                    print()
                    print("Enter Something!")
                    print()
                else: break
            while 1==1:
                keyWord=input("Enter keyword : ").lower()# Enter the message to be encoded / made sure that the input is turned all to lower case
                if keyWord == '':
                    print()
                    print("Enter Something!")
                    print()
                else: break
            encode = encrypt(text, keyWord) # runs the defined encrypt variable with the inputs 'text' and 'keyWord'
            myFile = open('data.txt', 'w')  # This opens the file called 'data.txt' so we can write to it
            myFile.write(encode) #writes the encoded word to the text file named 'data.txt'

            myFile.close
           #print ("encoded word is --> " + encode)



        elif decision == '2':
            myFile = open("data.txt","r")  # This opens the file called 'data.txt' so we can read it
            encodedTextSaved=myFile.readlines()  # This reads the encoded text into the variable encodedTextSaved
            myFile.close()
            decodedText=encodedTextSaved[0]
            while 1==1:
                keyWord=input("Enter keyword : ").lower()# Enter the message to be encoded / made sure that the input is turned all to lower case
                if keyWord == '':
                    print()
                    print("Enter Something!")
                    print()
                else: break
            decode = decrypt(decodedText, keyWord)# runs the defined decrypt variable with the inputs 'decodedText' and 'keyWord'
            print ("the decoded text is > " + decode)
        elif decision == 'no' or 'No': # if the user does not want to carry on then it quits the program
            print("Okay then....Bye")
            break
        elif decision == '3': # if the user chooses option 3 it breaks the while loop and closes the program
            print()
            break
        else: print("Invalid") # if user enters anything that is not what the program asks for it gives the user a second chance as the input is 'invalid'



if start == 'n': # if the user enters 'n' it does not proceed with the code and quits it 
    print()
    print("We hope that you shall use this program again in the not so distant future")

【问题讨论】:

请不要将文字包含在图片中。 【参考方案1】:

您的加密使用文本文件的默认编码不支持的字符。在 Python 3 中,文本字符串是 Unicode,因此在将它们写入文件时指定编码。 utf8 处理所有 Unicode 字符,因此是一个不错的选择。还要确保调用 myFile.close(缺少括号):

myFile = open('data.txt', 'w',encoding='utf8')
myFile.write(encode)
myFile.close()

在读回数据时也要指定相同的编码:

myFile = open("data.txt","r",encoding='utf8')

【讨论】:

谢谢!我真的很感谢你的帮助

以上是关于使用空格时出现 UnicodeEncodeError的主要内容,如果未能解决你的问题,请参考以下文章

爬过链接时出现scrapy错误[关闭]

BigQuery 在创建实体化视图时出现“缺少空格”错误

编写python代码时出现SyntaxError: invalid character in identifier的解决方法

编写python代码时出现SyntaxError: invalid character in identifier的解决方法

将Wix 3.0迁移到Wix 4.0时出现错误:WXCP0006:此节点前的空格不正确(WhitespacePrecedingNodeWrong)

学习Flask时出现的各种Typo错误