Skip to main content
 首页 » 编程设计

python之Unicode解码错误: 'utf8' codec can't decode byte 0x80 in position 0: invalid start byte

2025年05月04日10insus

我知道有很多关于编码解码的问题,但我似乎没有弄明白:

def content(title, sents): 
sent_elems = [] 
for sent_i, sent in enumerate(sents, 1): 
 
 
    elem = u"<a name=\"{i}\">[{i}]</a> <a href=\"#{i}\" id={i}>{text}</a>".format(i=sent_i, text=sent.text) 
    sent_elems.append(elem) 
doc = u"""<html> 
<head> 
<title>{title}</title> 
</head> 
<body>{elems}</body> 
</html>""".format(title=title, elems="\n".join(sent_elems)) 
 
return doc 

在极少数情况下调用内容函数会出现此错误(在我的整个数据集中可能出现一两次):

 File "processing.py", line 68, in score_summary 
self._write_config(references, summary) 
  File "processing.py", line 56, in _write_config 
reference_files = self._write_references(references, reference_dir) 
  File "processing.py", line 44, in _write_references 
f.write(rouge_summary_content(reference.id, reference.sents)) 
  File "processing.py", line 154, in rouge_summary_content 
</html>""".format(title=title, elems="\n".join(sent_elems)) 
UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 0: invalid start byte 

我已经更改为:

sent_elems.append(elem.decode("utf-8", "ignore")) 

还有

sent_elems.append(elem.decode("utf-8", "replace")) 

还是一样的错误。

我查看了数据,但无法弄清楚为什么会发生这种情况。我检查了发生此错误的文件,但仍然没有非 utf8 字符。

我还在我的文件中添加了这个:

import sys 
reload(sys) 
sys.setdefaultencoding("utf-8")  

问题依然存在。有什么建议吗?

请您参考如下方法:

我的标题是 chr(65+index),所以当它遍历所有大写字母时,它会打印一些非 utf-8 字符。我将其更改为 str(index) 并解决了我原来的问题。