【问题标题】:How to Replace Unicode Character Codes in TXT Output如何替换 TXT 输出中的 Unicode 字符代码
【发布时间】: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 函数中以相同标准对输出进行编码应该可以工作。

https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/

【问题讨论】:

    标签: python python-3.x unicode beautifulsoup


    【解决方案1】:

    您获得使用\u 编码的非ASCII 字符的原因是您使用的是json.dumps。从the docs 可以看出,ensure_ascii 参数默认为True,如果为真,“输出保证所有传入的非 ASCII 字符都被转义”。

    因此,您可以将ensure_ascii=False 添加到所有dumps 调用中。

    但实际上,你为什么首先使用json.dumps?您输出的格式不是 JSON 文件。事实上,它似乎是为人类而不是计算机消费而设计的。那么为什么你想要额外的引号、转义字符等来使它的部分 JSON 可解析,即使整个不是?如果您不这样做,它会更简单,并且可能会产生更好的输出:

    content = dict.get("content")
    loc_no = str(dict.get("location_number"))
    page_no = str(dict.get("page_number"))
    f.write("\n")
    f.write(content + " " + "(" + page_no + ", " + loc_no + ")" +"\n")
    

    ……或者,甚至更好:

    content = dict.get("content")
    loc_no = dict.get("location_number")
    page_no = dict.get("page_number")
    f.write("\n")
    f.write("{} ({}, {})\n".format(content, page_no, loc_no)
    

    当我们这样做时,调用您的字典 dict 会让人感到困惑(这意味着您无法在函数的其余部分访问 dict 构造函数,而不会遇到那些会让您彻夜难眠的错误之一调试然后感觉自己像个白痴)。

    另外,你为什么在这里使用get("content")?

    如果您不必担心没有content 的情况,只需使用["content"]——或者更简单,只需将dict 传递给format_map:

    for ref in refs:
        f.write("\n{content} ({page_number}, {location_number})\n".format_map(ref))
    

    如果您确实需要担心这种情况,那么您肯定需要一些适当的对人类有意义的字符串,而不是None。例如:

    for ref in refs:
        content = ref.get("content", "-- content missing --")
        page_no = ref.get("page_number", "N/A")
        loc_no = ref.get("location_number", "N/A")
        f.write("\n{} ({}, {})\n".format(content, page_no, loc_no)
    

    【讨论】:

    • 感谢您花时间剖析我的代码并提供一些详细的建议。我没有使用 json.dumps 的充分理由,除了我在谷歌上搜索“如何将字典写入文件”并在这里看到这个......quora.com/How-do-I-write-a-dictionary-to-a-file-in-Python。
    • 没听说过format_map。我认为在字典的键值对中检索值的最佳方法是使用该 dictionary.get("key") 内容。我也会试试看的。
    猜你喜欢
    • 2022-11-19
    • 2011-09-15
    • 2017-12-09
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 2016-07-04
    • 1970-01-01
    相关资源
    最近更新 更多