import re
import sys
import os
def convert_numpy_str_to_latex(file_path):
"""
NumPy配列形式のテキストファイルを読み込み、LaTeXのbmatrix形式の文字列を返す関数
"""
# ファイルが存在するか確認
if not os.path.exists(file_path):
return f"エラー: ファイル '{file_path}' が見つかりません。"
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# 1. 前処理: 角括弧 [ ] をすべて空白に置換して削除
# これにより、[[ 1. 0. ]] のような入れ子構造もフラットなテキストになります
cleaned_content = content.replace('[', ' ').replace(']', ' ')
# 2. 行ごとに分割
lines = cleaned_content.strip().split('\n')
latex_rows = []
for line in lines:
# 空白で分割して数値のリストを取得(連続する空白は自動的に無視されます)
values = line.split()
# print(type(values[0]))
# 空行の場合はスキップ
if not values:
continue
# 値のフォーマット処理
formatted_values = []
for v in values:
if('e' in v):
[mantissa, exponent] = v.split('e')
if(float(exponent) == 0):
mantissa = int(float(mantissa))
formatted_values.append(str(mantissa))
else:
mantissa = round(float(mantissa), 2)
mantissa = str(mantissa)
formatted_values.append(mantissa + ' \\times 10^{' + str(int(exponent)) + '}')
else:
try:
# 浮動小数点数として解釈できるか試みる
float_val = float(v)
# 整数の場合(例: 1.0, 1.0000e+00)は整数として表示("1")
if float_val.is_integer():
formatted_values.append(str(int(float_val)))
else:
# 指数表記などの場合でも、必要に応じて一般的な小数表記にするなどの処理が可能
# ここでは元の文字列をそのまま使いつつ、末尾の不要なドットだけ削除する例を示す
# もし常に固定小数点表記にしたい場合は "{:.4f}".format(float_val) などに変更してください
formatted_values.append(v.rstrip('.') if v.endswith('.') and '.' in v else v)
except ValueError:
# 数値変換できない場合はそのまま追加
formatted_values.append(v)
# 3. 各数値をLaTeXの列区切り文字 '&' で結合
row_str = " & ".join(formatted_values)
latex_rows.append(row_str)
# 4. 全体をLaTeXの行区切り文字 '\\' で結合し、bmatrix環境で囲む
matrix_body = " \\\\\n ".join(latex_rows)
latex_output = (
"\\begin{bmatrix}\n"
f" {matrix_body}\n"
"\\end{bmatrix}"
)
return latex_output
if __name__ == "__main__":
# 読み込むファイル名(ここを変更してください)
input_filename = "/Users/boyangchen/Desktop/MyPythonFiles/Latex_converter_kit/src.txt"
# 出力するファイル名(オプション)
output_filename = "/Users/boyangchen/Desktop/MyPythonFiles/Latex_converter_kit/output.tex"
print(f"--- {input_filename} を読み込んでいます ---")
result = convert_numpy_str_to_latex(input_filename)
print("\n--- LaTeX出力結果 ---\n")
print(result)
# 結果をファイルに保存
with open(output_filename, 'w', encoding='utf-8') as f:
f.write(result)
print(f"\n--- {output_filename} に保存しました ---")
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme