2

Excel スプレッドシートから .csv ファイルを取得し、LaTeX テーブルに適した形式に変換できるスクリプトを Python 2.7.3 で作成しようとしています。したがって、ファイルを読み取り、データを新しいテキスト ファイルに書き込みたいのですが、カンマをアンパサンドに置き換え、各行の末尾に二重のバックスラッシュを追加します。

例:
入力

A1,A2,A3  
B1,B2,B3  
C1,C2,C3

望ましい出力

A1 & A2 & A3 \\
B1 & B2 & B3 \\
C1 & C2 & C3 \\

これが私が今持っているものです:

old_file = open(selected_file, "r")
new_file = open("texified_" + selected_file.replace("csv","txt"), "w")
#Creates new file with format texified_selected_file.txt

for line in old_file:
    new_file.write(line.replace(",", " & ") + r" \\")

new_file.close()
old_file.close()

現在、コンマをアンパサンドに適切に置き換えていますが、二重のバックスラッシュは追加していません。これはバックスラッシュに特別な意味があるからだと思っていたのですが、生の文字列にしてもうまくいきません。ただし、最終行の最後に追加します。

実際の出力

A1 & A2 & A3   
B1 & B2 & B3  
C1 & C2 & C3 \\
4

2 に答える 2

1

これはおそらくnewline、ファイルの各行の終わりにすでにあり、の終わりにはないために発生していlast lineます。

を追加する前に、それを削除して//から、改行を個別に追加してみてください。-

import os
ls = os.linesep

for line in old_file:
    new_file.write(line.replace(",", " & ").rstrip() + r' \\ ' + ls)
于 2013-02-10T21:07:40.497 に答える
0

あなたのコード(または入力データ)のどこが悪いのかわかりませんが、おそらくこれと同じようにします(おそらく冗長ではありません):

for line in old_file:
    line = line.strip()     # remove newline/whitespace from begin and end of line
    line = line.split(',')  # get comma-separated values
    line = " & ".join(line) # make it ampersand-separated values
    line += r" \\"          # add latex line break
    line += "\n"            # add file line break
    new_file.write(line)

またはこの方法:

import jinja2

# define the latex template
template_str = r"""
\documentclass{article}
\begin{document}
\begin{table}
  \centering
  \begin{tabular}{ccc}
%{ for line in table %} %{{line[0]%}} & %{{line[1]%}} & %{{line[2]%}} \\ 
%{ endfor %}
  \end{tabular}
\end{table}
\end{document}

"""

# initialize the rendering engine
renderer = jinja2.Environment(
  block_start_string = '%{',
  block_end_string = '%}',
  variable_start_string = '%{{',
  variable_end_string = '%}}'
)
template = renderer.from_string(template_str)

# bring the data array into shape
lines = [line.strip().split(',') for line in old_file]

# generate the tex source code
with open("test.tex", 'w+') as f:
  f.write(template.render(table=lines))

これらのリソースもご覧ください。

于 2013-02-10T21:41:52.430 に答える