open() 无法正确解析文本文件中的字符 [重复]

问题描述 投票:0回答:0

我在文本文件中有以下段落:

I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I—
I took the one less traveled by,
And that has made all the difference.

我需要将其作为字符串读取以进行进一步操作。

当我在我的 Python 控制台中阅读它时,解析器无法解析第三行的最后两个字符

I—
,因为它们出现在这里。相反,它显示以下符号
Iâ€
。为了更清楚,我将第三行的结果整体复制在这里:

Two roads diverged in a wood, and Iâ€

但是,如果我使用复制/粘贴在 Python 脚本中复制此文本并将其定义为这样的字符串:

test_str = """I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I—
I took the one less traveled by,
And that has made all the difference.
"""

然后它就没有问题并正确解析这些字符。

要复制我的问题,您需要将此段落复制到一个新的文本文件中

poem_new.txt
保存它然后使用以下代码打开:

with open(cwd + "\\data\\vid_13_files_exercises\\poem_new.txt", "r") as f:
    poem_str = f.read()

或者要复制完全相同的环境,您可以在此处从我的驱动器下载文件 (https://drive.google.com/file/d/1I5r9XWLOKP-MCFfVcvUCKadi9ESZ8TwW/view?usp=sharing),然后使用代码进行解析以上。

要将文件解析为字符串,我使用以下代码:

with open(cwd + "\\data\\vid_13_files_exercises\\poem_new.txt", "r") as f:
    poem_str = f.read()

我的 Python 版本在 Windows 10 64 位上是 3.10.8

python python-3.x string file-io
© www.soinside.com 2019 - 2024. All rights reserved.