我在运行时将数据填入字典中。需要帮助将这些数据填充到 Latex 中的表中。
表格的代码片段:
f.write('\\end{itemize}\n')
f.write('\\begin{table}[ht]')
f.write('\\caption{Resolved issues}')
f.write('\\centering')
f.write('\\begin{tabular}{c c} ')
f.write('\\hline\\hline')
f.write(' Issue-Id & Summary \\\ [0.5ex] ')
f.write('\\hline ')
f.write(' 123 & Summary1 \\\ ')
f.write(' 456 & Summary2 \\\ [1ex] ')
f.write('\\hline ')
f.write('\\end{tabular}')
f.write('\\label{table:nonlin}')
f.write('\\end{table}')
我已将 Issue-id 硬编码为 123 和 456。同样,Summary 为 Summary1 和 Summary2。
我的字典内容是这样的:
{'35871': ['Bad Loop Optimizations'], '35398': ['Bad long loop expansion], '36702': ['Crash reading a file']}
任何帮助深表感谢。
答案1
欢迎来到 TeX.SX! 据我了解,你的问题似乎与 python 更相关,而不是与 TeX 更相关!
尝试以下代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Shanthi = {'35871': ['Bad Loop Optimizations'], '35398': ['Bad long loop expansion'], '36702': ['Crash reading a file']}
with open("./Shanthi.tex", "w") as f:
f.write('\\begin{table}[ht]\n\\caption{Resolved issues}\n\\centering\n')
f.write('\\begin{tabular}{@{}c c@{}}\n\t\\toprule\n\t{\\bfseries Issue-Id} & {\\bfseries Summary} \\\\\n\t\\midrule\n\t')
f.write("\\\\ \n\t".join(["{} & {}".format(_k, ", ".join(_v)) for _k, _v in sorted(Shanthi.items())]))
f.write('\\\\\n\t\\bottomrule\n\\end{tabular}\n\\label{table:nonlin}\n\\end{table}')
它生成一个Shanthi.tex
文件,其中包含:
\begin{table}[ht]
\caption{Resolved issues}
\centering
\begin{tabular}{@{}c c@{}}
\toprule
{\bfseries Issue-Id} & {\bfseries Summary} \\
\midrule
35398 & Bad long loop expansion\\
35871 & Bad Loop Optimizations\\
36702 & Crash reading a file\\
\bottomrule
\end{tabular}
\label{table:nonlin}
\end{table}
因此,您可以在文件\input{Shanthi.tex}
中使用main
。请务必\usepackage{booktabs}
在序言中添加,以便获得漂亮的表格(例如参见此处)。
提出的小改进projetmbc
(f 字符串仅适用于 python ≥ 3.6)
#!/usr/bin/env python
Shanthi = {
'35871': ['Bad Loop Optimizations'],
'35398': ['Bad long loop expansion'],
'36702': ['Crash reading a file']
}
with open("./Shanthi.tex", "w") as f:
backreturn = "\\\\\n" + " "*8
content = backreturn.join([
f"{_k} & {', '.join(_v)}"
for _k, _v in sorted(Shanthi.items())
])
f.write(f"""
\\begin{{table}}[ht]
\\caption{{Resolved issues}}
\\centering
\\begin{{tabular}}{{@{{}}c c@{{}}}}
\\toprule
{{\\bfseries Issue-Id}} & {{\\bfseries Summary}} \\\\
\\midrule
{content}\\\\
\\bottomrule
\\end{{tabular}}
\\label{{table:nonlin}}
\\end{{table}}
""".strip())
处理较大的单元格内容、长表格和 ID 重复项
只需使用-column (或)longtable
代替table
+即可。用元组列表替换字典。tabular
p
m
你的 Python 脚本:
#!/usr/bin/env python
Shanthi = [
('35871', 'Bad Loop Optimizations'),
('35398', 'Bad long loop expansion'),
('36702', 'Crash reading a file'),
('2692415', 'connect fatal error : System Mixing wild card named port connection (.*) and position wrong while instanced with signals concatenated and tool generated "option.f"'),
('35871', 'Bad Loop Optimizations'),
('35398', 'Bad long loop expansion'),
('36702', 'Crash reading a file'),
('2692415', 'connect fatal error : System Mixing wild card named port connection (.*) and position wrong while instanced with signals concatenated and tool generated "option.f"'),
('35871', 'Bad Loop Optimizations'),
('35398', 'Bad long loop expansion'),
('36702', 'Crash reading a file'),
('2692415', 'connect fatal error : System Mixing wild card named port connection (.*) and position wrong while instanced with signals concatenated and tool generated "option.f"'),
('0', '\\lipsum[1]'),
('35871', 'Bad Loop Optimizations'),
('35398', 'Bad long loop expansion'),
('36702', 'Crash reading a file'),
('2692415', 'connect fatal error : System Mixing wild card named port connection (.*) and position wrong while instanced with signals concatenated and tool generated "option.f"'),
]
with open("./Shanthi.tex", "w") as f:
backreturn = "\\\\\n" + " "*4
content = backreturn.join([
f"{_tuple[0]} & {_tuple[1]}"
for _tuple in Shanthi
])
f.write(f"""
\\begin{{longtable}}{{@{{}}cp{{.7\\textwidth}}@{{}}}}
\\caption{{Resolved issues\\label{{table:nonlin}}}}\\\\
\\toprule
{{\\bfseries Issue-Id}} & {{\\bfseries Summary}} \\\\ \\midrule
\\endfirsthead
\\caption{{Resolved issues (continued)}}\\\\
\\toprule
\multicolumn{{2}}{{l}}{{\\scriptsize\\emph{{\\ldots{{}} continued}}}}\\\\
{{\\bfseries Issue-Id}} & {{\\bfseries Summary}} \\\\ \\midrule
\\endhead
\\multicolumn{{2}}{{r}}{{\\scriptsize\\emph{{to be continued\ldots}}}}\\\\
\\bottomrule
\\endfoot
\\bottomrule
\\endlastfoot
{content}\\\\
\\end{{longtable}}
""".strip())
它会生成一个Shanthi.tex
文件,您可以在其中调用它main.tex
:
\documentclass[a4paper,12pt]{article}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{lipsum}
\begin{document}
\input{Shanthi.tex}
\end{document}
答案2
顺便说一下
表格的代码片段:
f.write('\end{itemize}\n')
f.write('\begin{table}[ht]')...
当你 1) 将所需输出连接成一个长字符串,并且 2) 将其写出一次时,你的 Python 代码会变得更易读且更易于维护。请参阅https://www.w3schools.com/python/gloss_python_string_concatenation.asp有关详细信息,以及有关此策略的一些 Python 伪代码,保留潜在的反斜杠问题:
% assembling all required output
s = '\\end{itemize}\n'
s += '\\begin{table}[ht]'
s += '\\caption{Resolved issues}'
s += ...
% ...
f.write(s) % that's all, folks. "Just one f.write" (Like in 'The hunt for red october')
最好的祝愿
答案3
NBUR 的答案采用的是元组列表,而不是字典。问题要求将字典转换为 LaTex 表。以下是直接从字典转到 LaTex 表的改编代码:
def dict_to_latex_table(params:dict,key_header:str,value_header:str,caption:str):
tuples=dict_to_latex_tuples(params)
with open("latex/Tables/params_table.tex", "w") as f:
backreturn = "\\\\\n" + " "*4
content = backreturn.join([
f"{_tuple[0]} & {_tuple[1]}"
for _tuple in tuples
])
f.write(f"""
\\begin{{longtable}}{{@{{}}cp{{.7\\textwidth}}@{{}}}}
\\caption{{{caption}\\label{{table:nonlin}}}}\\\\
\\toprule
{{\\bfseries {key_header}}} & {{\\bfseries {value_header}}} \\\\ \\midrule
\\endfirsthead
\\caption{{{caption} (continued)}}\\\\
\\toprule
\multicolumn{{2}}{{l}}{{\\scriptsize\\emph{{\\ldots{{}} continued}}}}\\\\
{{\\bfseries {key_header}}} & {{\\bfseries {value_header}}} \\\\ \\midrule
\\endhead
\\multicolumn{{2}}{{r}}{{\\scriptsize\\emph{{to be continued\ldots}}}}\\\\
\\bottomrule
\\endfoot
\\bottomrule
\\endlastfoot
{content}\\\\
\\end{{longtable}}
""".strip())
def flatten_dict(some_dict:dict):
flat_dict={}
# Flatten dict
for key, value in some_dict.items():
if isinstance(value,dict):
for newKey, newValue in value.items():
flat_dict[newKey] = newValue
else:
flat_dict[key]=value
print(f'flattend_params={flat_dict}')
return flat_dict
def dict_to_latex_tuples(some_dict: dict):
flat_dict=flatten_dict(some_dict)
tuples=[]
for key,value in flat_dict.items():
if isinstance(key,str):
key=key.replace("_"," ")
if isinstance(value,str):
value=value.replace("_"," ")
tuples.append((key,value))
return tuples
此外,列标题和标题也已参数化。并且用空格代替下划线。