0

我有一个 LaTeX 文件,我想在表单字段中显示它。输入文件:

...
\begin{center}
    \vspace{-5mm}
    \noindent
    \textbf{\large Thank You! for Using}
\end{center}
...

我在 python 中使用readlines()

'\\begin{center}' '\n'

... 等等。

我希望删除转义字符 < no '\n' '\'' '\t' etc> 以便可以将读取的内容放入表单字段。怎么做到呢?

4

2 回答 2

0

我不太确定你是否真的想删除所有转义字符\n每行末尾的所有转义字符。这是许多 python 程序员第一次阅读文件时的常见问题,我前一段时间自己也遇到过。

readlines()保留尾随\n,以便简单"".join(lines)地恢复原始文件内容。

\n只需从每行中删除尾随。

# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys

lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
    print line
    lines1.append(line)
fh.close()

lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
    line = line.rstrip()
    print line
    lines2.append(line)
fh.close()

输出将是

# -*- coding: utf-8 -*-

"""

Sample for readlines and trailing newline characters

"""

import sys



lines1 = []

fh = open(sys.argv[0],"r")

for line in fh.readlines():

    print line

    lines1.append(line)

fh.close()



lines2 = []

fh = open(sys.argv[0],"r")

for line in fh:

    line = line.rstrip("\n")

    print line

    lines2.append(line)

fh.close()


# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys

lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
    print line
    lines1.append(line)
fh.close()

lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
    line = line.rstrip("\n")
    print line
    lines2.append(line)
fh.close()

你也可以写line.rstrip("\n")明确地只去除换行符而不是所有的空白字符。

于 2013-01-04T06:55:01.870 回答
0

您可以使用replace适用于 Python 字符串的函数。

$> a = 'xyz\nbcd'
$> b = a.replace('\n','') # b would be 'xyzbcd'
于 2013-01-04T06:32:52.247 回答