我的Python程序已经获得UnicodeDecodeError
,所以我想我可以在我的代码中使用try-except来绕过它。但是,即使使用try-except,我仍然会得到UnicodeDecodeError
而我的程序只是拒绝运行。我使用try-except错误吗?
这是我的代码:
combinedCorpus=[]
line = text.readline().lower()
words_filtered = [word for word in line.split() if len(word) >= 3]
try:
combinedCorpus.append((words_filtered, "positive")) #this is where my problem is
except UnicodeDecodeError:
print "Error appending to combinedCorpus."
这是我的追溯:
Traceback (most recent call last):
File "C:\Users\???\Desktop\python\App.py", line 38, in <module>
print json.dumps(combinedCorpus,indent=2)
File "C:\Python27\lib\json\__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "C:\Python27\lib\json\encoder.py", line 209, in encode
chunks = list(chunks)
File "C:\Python27\lib\json\encoder.py", line 431, in _iterencode
for chunk in _iterencode_list(o, _current_indent_level):
File "C:\Python27\lib\json\encoder.py", line 332, in _iterencode_list
for chunk in chunks:
File "C:\Python27\lib\json\encoder.py", line 332, in _iterencode_list
for chunk in chunks:
File "C:\Python27\lib\json\encoder.py", line 313, in _iterencode_list
yield buf + _encoder(value)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 4-5: invalid continuation byte
答案 0 :(得分:2)
我找到了解决问题的方法。 unicode错误实际上来自代码中的后期。
combinedCorpus.append((words_filtered, "positive"))
print json.dumps(combinedCorpus,indent=2)
显然,json.dumps与我的文字不兼容。咦。
感谢所有回答和评论的人!
答案 1 :(得分:-1)
请注意,Exception逐级引发,我假设程序抛出的异常不是UnicodeDecodeError
。如果您尝试顶级异常(应为Exception
),则应该可以正常工作。
如下所示:
try:
combinedCorpus.append((words_filtered, "positive"))
except Exception as e:
print "Error appending to combinedCorpus."
如果这样有效,你应该试着找出真正的异常是什么,并尝试抓住那个。