将反斜杠放入字符串中

时间:2018-09-14 01:31:52

标签: python-3.x file latex

我有大量的长文本文件,我想将其转换为LaTex格式的表。这是其中一个文件的简短示例:

List of the best combinations (with |r-value| > 0.5)
Combination &   r value &   no.obs. &   Kendall's tau
============================================================
B - V   &   0.580019    &   11863   &   1.000000
B - R   &   0.574867    &   11863   &   1.000000
V - B   &   -0.580019   &   11863   &   1.000000
R - B   &   -0.574867   &   11863   &   1.000000

Highest r-value of 0.580019 occurred for B - V
Lowest r-value of -0.580019 occurred for V - B

我需要将其转换为LaTex文档中的表,因此需要将其格式化为:

List of the best combinations (with |r-value| > 0.5)\\
\hline
Combination &   r value &   no.obs. &   Kendall's tau\\
============================================================\\
B - V   &   0.580019    &   11863   &   1.000000\\
\hline
B - R   &   0.574867    &   11863   &   1.000000\\
\hline
V - B   &   -0.580019   &   11863   &   1.000000\\
\hline
R - B   &   -0.574867   &   11863   &   1.000000\\
\hline

Highest r-value of 0.580019 occurred for B - V\\
Lowest r-value of -0.580019 occurred for V - B\\

实际文件的长度为数十行,因此手动进行操作是不切实际的。

我尝试过

filename = file+'.txt'
with open(filename, 'r') as infile:
    new_filename = file+'_table.txt'
    with open(new_filename, 'w') as outfile:
        lines = infile.readlines()
        for line in lines:
            end_of_line = r'\\'
            outfile.write(line + end_of_line)
            outfile.write(r'\\hline')

以及here的建议,但我的输出是

\List of the best combinations (with |r-value| > 0.5)
\Combination    &   r value &   no.obs. &   Kendall's tau
\============================================================
\B - V  &   0.580019    &   11863   &   1.000000
\B - R  &   0.574867    &   11863   &   1.000000
\V - B  &   -0.580019   &   11863   &   1.000000
\R - B  &   -0.574867   &   11863   &   1.000000
\
\Highest r-value of 0.580019 occurred for B - V
\Lowest r-value of -0.580019 occurred for V - B
\
\

如何将\\\hline逐字插入outfile中?还是可以使用其他工具转换为LaTex格式?

2 个答案:

答案 0 :(得分:1)

.txt文件中,句子末尾实际上有一个\n! 为了在句子的末尾添加一些内容,我们应该注意这一点。

我认为您可以在“ for line in lines”中添加另一行来解决此问题!      line = line.replace("\n", " ") end_of_line = r'\\' ...并按照

如果要创建另一行,请使用:      outfile.write('\n') outfile.write(r'\hline') outfile.write('\n')

我帮您帮忙。

答案 1 :(得分:0)

最终将其修复为:

with open(filename, 'r') as infile:
        new_filename = file+'_table.txt'
        with open(new_filename, 'w') as outfile:
            lines = infile.readlines()
            outfile.write(r'\begin{tabular}{|c|c|c|c|}')
            for line in lines[1:-3]:
                if line.startswith('='):
                    pass
                else:
                    line = line.replace('\n', ' '+r'\\'+'\n')
                    outfile.write(line)
                    outfile.write(r'\hline' + '\n')
            outfile.write(r'\end{tabular}')

用于处理我的文件的详细信息。