我有一个文本,其中有一个摘要。我用一些正则表达式来获取这个摘要,因为文本总是具有相同的结构
在摘要中有一个句子“NAME被归类为....”,我必须用文本中抓取的标题替换它,并用逗号分隔的word1和word2组成。只要我这样做,它工作正常(因此我不会添加完整的代码,因为它非常大,我不能这样做,而且无论如何问题不在我将提供的范围之外。
我需要根据word1添加unicode字符\ u2191或\ u2193,它与字典中的正值或负值相关联。这必须在替换句子之前完成。
我的代码基本上如下:
import re
import io
file=open(Summaries_file,'a')#also tried open(Summaries_file,'a', encoding="UTF_16_LE") and file=io.open(Summaries_file,'a', encoding="UTF_16_LE")
code_dict["page"]="Word1\u2191"
page="page"
summary = "Data is: 111919919. Name is classified as an infered value".
print(summary)
#OUTPUT>"Data is: 111919919. Name is classified as an infered value".
title= "Word1, Word2"
#this is the part added to regular code>>>>
titlelist=title.split(",")
if titlelist[0]==code_dict[page]:
titlelist[0]=code_dict[page]+"\u2191"
title=str(titlelist)
print(titlelist[0])
#OUTPUT>"Word1↑"#It displays the arrow well
print(title) #ok, too.
#OUTPUT>"Word1↑, Word2"
#We go back to the end of the normal code
insert=re.compile("is classified as")
print(type(summary))
#<class 'str'>
summary=str(insert.sub(title, summary))
print(summary)
#OUTPUT>"Data is: 111919919. Name Word1↑, Word2 an infered value".
print("passed")
file.write(title+'\n')
file.write(summary+'\n')
然后回溯(最近一次呼叫最后一次):
File "<ipython-input-1-6bc913872cc9>", line 1, in <module>
runfile('C:/Python Scripts/txtad.py', wdir='C:/Users/Laurent/Documents/Python Scripts')
File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 88, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Python Scripts/txtad", line 380, in <module>
file.write(title+'\n')
File "C:\Anaconda3\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 '\u2191' in position 11: character maps to <undefined>
现在,我无法解决这个问题,而且我非常认真地坚持这一点 我不知道为什么它首先写入失败,因为它很好地显示了符号,并且我在某些测试中明确地编码到正确的系统,甚至用正确的编码打开文件。
我尝试了各种你可以阅读的内容:
确实原始代码更大,但我尝试了这个并且它的工作方式相同,输入类型严格相同。
我读过这些:
UnicodeEncodeError: 'charmap' codec can't encode character '\u2010': character maps to <undefined>
UnicodeEncodeError: 'charmap' codec can't encode characters
Python, Unicode, and the Windows console
python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>
最后,它们比其他任何东西都更令人困惑。
无论如何问题不在于控制台,就像那些其他帖子一样,因为问题出现时没有显示写入指令,此外,这个字符在我的控制台上显示得很好...
我真的不知道发生了什么以及如何解决这个问题
感谢您的见解。
答案 0 :(得分:0)
我终于通过阅读本文和链接文章解决了这个问题 TadhgMcDonald-Jensen的评论; Writing Unicode text to a text file?
实际上我只需要在为每个字符串写入时打开(文件,“wb”)和编码(因为它们不是字节)。 我想我可以使用io或编解码器导入并使用向后兼容性打开。