【发布时间】:2018-07-22 02:00:20
【问题描述】:
我正在使用 Beautiful Soup 库来解析网页的内容并将结果打印到 .txt 文件中。这主要有效,但我无法摆脱文本输出中出现的某些 unicode 字符代码。例如:
“未能调查客户终端的问题。”
我一直在使用“io”库将输出编码为utf-8。我已经尝试将编码更改为ascii,但这也不起作用。
def open_file(file):
with open((file), encoding='utf-8') as input_data:
global soup
soup = BeautifulSoup(input_data)
return soup
# stuff happens here to parse the html and prepare a list of dictionaries containing the content I want to print.
# this prepares the output
def dict_writer(dict_list, filename):
with io.open('%s.txt' % filename, 'w', encoding="utf-8") as f:
for dict in dict_list:
content = json.dumps(dict.get("content"))
loc_no = json.dumps(dict.get("location_number"))
page_no = json.dumps(dict.get("page_number"))
f.write("\n")
f.write(content + " " + "(" + page_no + ", " + loc_no + ")" +"\n")
f.write("\n")
我阅读了下面的文章,试图大致了解字符编码的工作原理。似乎如果我在 open_file 函数中对内容进行编码,则在 dict_writer 函数中以相同标准对输出进行编码应该可以工作。
【问题讨论】:
标签: python python-3.x unicode beautifulsoup