在Python中将字符串转换为latex表格式

在Python中将字符串转换为latex表格式,python,latex,scikit-learn,Python,Latex,Scikit Learn,我有以下关于使用Sklearn的机器学习算法的性能报告: >>> from sklearn.metrics import classification_report >>> y_true = [0, 1, 2, 2, 2] >>> y_pred = [0, 0, 2, 2, 1] >>> target_names = ['class 0', 'class 1', 'class 2'] >>> print(c

我有以下关于使用Sklearn的机器学习算法的性能报告:

>>> from sklearn.metrics import classification_report
>>> y_true = [0, 1, 2, 2, 2]
>>> y_pred = [0, 0, 2, 2, 1]
>>> target_names = ['class 0', 'class 1', 'class 2']
>>> print(classification_report(y_true, y_pred, target_names=target_names))
             precision    recall  f1-score   support

    class 0       0.50      1.00      0.67         1
    class 1       0.00      0.00      0.00         1
    class 2       1.00      0.67      0.80         3

avg / total       0.70      0.60      0.61         5
我正在使用
file.write(report)
分类报告
保存为文本文件,但我希望将其保存为TEX table格式,如下所示:

\begin{table}[htbp]
  \centering
  \caption{Add caption}
    \begin{tabular}{rrrrr}
    \toprule
          & precision & recall & f1-score & support \\
    \midrule
          &       &       &       &  \\
    class 0 & 0.5   & 1     & 0.67  & 1 \\
    class 1 & 0     & 0     & 0     & 1 \\
    class 2 & 1     & 0.67  & 0.8   & 3 \\
          &       &       &       &  \\
    avg/total & 0.7   & 0.6   & 0.61  & 5 \\
    \bottomrule
    \end{tabular}%
  \label{tab:addlabel}%
\end{table}%

有没有关于如何实现这一目标的建议?谢谢

表的页眉和页脚只是文本,所以我将跳过它们

获取
分类报告的输出
,并使用
str.splitlines()
将其拆分为行

因为您知道前两行和后两行包含的内容,所以可以将格式化工作集中在其余的行上

In [9]: lines = rep.splitlines()

In [10]: lines[2:-2]
Out[10]: 
['    class 0       0.50      1.00      0.67         1',
 '    class 1       0.00      0.00      0.00         1',
 '    class 2       1.00      0.67      0.80         3']

In [11]: cl = lines[2:-2]

In [19]: [ln.replace('class ', '').split() for ln in cl]
Out[19]: 
[['0', '0.50', '1.00', '0.67', '1'],
 ['1', '0.00', '0.00', '0.00', '1'],
 ['2', '1.00', '0.67', '0.80', '3']]

In [20]: cl = [ln.replace('class ', '').split() for ln in cl]

In [23]: for ln in cl:
    print('class ' + ' & '.join(ln) + r'\\')
   ....:     
class 0 & 0.50 & 1.00 & 0.67 & 1\\
class 1 & 0.00 & 0.00 & 0.00 & 1\\
class 2 & 1.00 & 0.67 & 0.80 & 3\\
avg
行的处理方式大致相同

In [25]: last = lines[-1]

In [29]: last[11:].split()
Out[29]: ['0.70', '0.60', '0.61', '5']

In [30]: numbers = last[11:].split()

In [31]: print('avg / total & ' + ' & '.join(numbers) + r'\\')
avg / total & 0.70 & 0.60 & 0.61 & 5\\
我建议跳过空行,尤其是因为您已经在使用
booktabs
包中的标尺


备选方案


如果有一种方法可以逐行从
sklearn
中获取数据,您可能想看看我编写的简单Python模块。

非常感谢,我明天将实现它!
In [25]: last = lines[-1]

In [29]: last[11:].split()
Out[29]: ['0.70', '0.60', '0.61', '5']

In [30]: numbers = last[11:].split()

In [31]: print('avg / total & ' + ' & '.join(numbers) + r'\\')
avg / total & 0.70 & 0.60 & 0.61 & 5\\