python - 尝试将 html 标记的文本写入 .txt 文件时出错 - Python
问题描述
尝试将包含 HTML 标记的字典键值写入文本文件时收到以下错误。
Traceback (most recent call last):
File "/Users/jackboland/PycharmProjects/NLTK_example/JsonToTxt.py", line 11, in <module>
data = json.load(json_data)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 293, in load
return loads(fp.read(),
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 10: invalid start byte
我有一组 JSON 文件。我成功地将该数据提取到 Python 字典中。然后,从那里,我确定值最长的字典键并将该值提取到文本文件中。该代码适用于最长字典键值为字符串的所有 JSON 文件。对于最长字典键值为 html 内容的文件,它会引发上述错误。
with open(path + file) as json_data:
data = json.load(json_data)
for value in data.values(): # gets the value of each dictionary key
value = str(value) # converts the value of each dictionary key to a string enabling counting total characters
vLength = len(value) # calculates the length of each value in every dictionary key to enable identifying only the longest of the key values
if vLength > 100: # if the length of a value is over 200 characters, it prints that, this insures capturing the opinion text no matter what dictionary key it is in
f = open(newpath + file[:-5] + ".txt", 'w+')
f.write(value)
f.close()
作为字符串的字典键值从字典中解析到文本文件中。只有字典键值包含不被写入文本文件的 html。
解决方案
Python 尝试将字节数组转换为 unicode 字符串。当它尝试这个时,它会遇到一个字节序列,该字节序列在 utf-8 编码的字符串中是不允许的(这里是位置 10 的 0xc0)。
尝试以二进制格式读取文件,以便文件的内容保留为字节。
with open(path + file, 'rb') as json_data:
//rest of the code
如果这不起作用,请手动指定编码格式。
例子 :
open(path + file, encoding="utf-8") as json_data
//rest of the code
您可以在此处获取各种编码格式。
推荐阅读
- sql - 带有 NULL NOT IN 子句的 TSQL,它会失败还是不会?
- python - 在 Python 中执行不同函数组合的最佳方法
- c# - 为什么 DisplayMemberPath 不起作用 在列表视图中使用?
- highcharts - Highcharts Multiple Series Drilldown to Multiple Series - 仅适用于该系列中的最后一组
- c# - UWP - 即使包含在功能中,DriveInfo 也会拒绝对可移动存储的访问
- java - SpringResourceTemplateResolver 的 setPrefix 方法没有设置请求的路径
- java - RecyclerView 新项目添加问题
- php - 在 PHP 中创建范围的两个随机数
- haskell - 评估 AST 中的变量赋值
- docker - 在 Docker 容器中运行 Celery 任务时出现问题