简体   繁体   English

在 Python 3.8 和 xlsxwriter 中写入 output 时,特殊字符(é、ê 等)将无法正确显示

[英]Special characters (é, ê, etc.) won't display correcly when writing output in Python 3.8 and xlsxwriter

I am using several text files to write output to an Excel file.我正在使用几个文本文件将 output 写入 Excel 文件。 Everything is working fine, except the formatting of special characters like é, ê, etc.一切正常,除了 é、ê 等特殊字符的格式。

Here is an example of the input text file:以下是输入文本文件的示例:

Please encourage Nehvandré to read aloud more often.请鼓励 Nehvandré 经常大声朗读。

This is how the specific piece of text is written to the Excel file:这是将特定文本写入 Excel 文件的方式:

Please encourage Nehvandré to read aloud more often.请鼓励 Nehvandré 经常大声朗读。

Here is the code I used to iterate through the text files and write the contents of the files to the Excel file.这是我用来遍历文本文件并将文件内容写入 Excel 文件的代码。

from pathlib import Path
import os
import xlsxwriter

txt_dir = r"D:\PYTHON_SCRIPTS\****\comment_output"
subfolder_name = [f.name for f in os.scandir(txt_dir) if f.is_dir()]
subfolder_path = [f.path for f in os.scandir(txt_dir) if f.is_dir()]

sub_index = 0
while sub_index < len(subfolder_name):
    row = 0
    col = 0
    workbook = xlsxwriter.Workbook(subfolder_path[sub_index] + f"\\{subfolder_name[sub_index]}.xlsx")
    worksheet = workbook.add_worksheet()
    for file in Path(subfolder_path[sub_index]).glob("*.txt"):
        with open(file, "r") as txt_file:
            encoded_file = file.read_text()
            worksheet.write(row, col, file.name[:-4])
            worksheet.write(row, col + 1, encoded_file)
            row += 1
        os.remove(file)
    workbook.close()
    sub_index += 1

How can I make the text in the Excel file appear the same as the text in the TXT file?如何使 Excel 文件中的文本与 TXT 文件中的文本显示相同? I am using Python 3.8我正在使用 Python 3.8

The comments of Enetrati and jmcnamara pointed me in the correct direction, I set the encoding of the text file when opening it: Enetrati 和 jmcnamara 的评论为我指明了正确的方向,我在打开文本文件时设置了它的编码:

 with open(file, encoding="utf-8", mode="r") as txt_file:

After this change the output was exactly as intended.在此更改之后,output 完全符合预期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM