1

我是 Python 新手,我正在使用我在此处找到的示例之一从文件中读取行并打印它们。我不明白为什么解释器会忽略\n转义序列:

文本文件:

以下哪些是您可能会在 PC 中找到的组件?(选择所有正确答案。)

A、中央处理器

B、主板

C. 键盘

答案:A、B 和 E。\n PC 内的常见组件包括\n CPU、主板和\n RAM

Python代码:

questions_fname="Test.txt"

with open(questions_fname, 'r') as f:
    questions = [line.strip() for line in f]

for line in questions:
    print (line)


f.close()

我得到的结果是这样的字符串:

Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM

我只是在寻找一种简单的方法来格式化长线以适应屏幕。

4

4 回答 4

4

您没有"\n"在字符串中,"\\n"因为您从文件中读取它。如果你想拥有"\n"那么你需要解码字符串。请注意,3.x 没有str.decode(),因此您不能使用 2.x 中的该机制。

3>> codecs.getdecoder('unicode-escape')('foo\\nbar')[0]
'foo\nbar'
于 2013-01-07T10:06:46.187 回答
0

尝试以下代码以获得想要的行为......

questions_fname = "Test.txt"

with open(questions_fname) as f:
    for line in f:
        line = line.rstrip().replace('\\n', '\n')
        print(line)

.rstrip()删除尾随空格,\n包括. 原因 对文件内容中您的序列的.replace()明确的、用户定义的解释\n- 捕获为可打印字符\,后跟n.

使用with构造时,f.close()会自动完成。

于 2013-01-07T11:09:45.830 回答
0

\是仅在 Python 脚本中的转义字符,而不是在文本文件中。在读取文本文件时,Python 将所有反斜杠转换为\\,因此在读取文件时,\n变为\\n不是换行符

于 2013-01-08T04:49:07.790 回答
-1

抱歉 - 这对 Python 3.x 无效(我正在查看标签),但我会留在这里作为参考 - 请参阅@Ignacio 的回答:https ://stackoverflow.com/a/14193673/1252759

如果您有效地获得了raw string包含文字字符的 a '\n',那么您可以重新解释该字符串以使其再次成为转义序列:

>>> a = r"Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM"
>>> print a
Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM
>>> print a.decode('string_escape')
Answers: A, B, and E. 
Common components inside a PC include 
the CPU,motherboard, and 
RAM

textwrap如果您想为某些显示器将线换行到某个宽度,您可能还想查看该模块...

于 2013-01-07T10:03:56.473 回答