如何在.txt中检测一个名称,然后在另一个fi中写入和扩展它

2024-09-30 00:38:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用python自动化latex。你知道吗

代码应该允许用户在.txt文件中编写内容,python可以从.txt中读取内容,然后将其写入.tex,最后,latex可以将.tex编译为PDF

一切都很好,直到需要一个数字。因为在乳胶里放一个数字需要特定的代码。你知道吗

例如:

用户在.txt中编写一个段落,如下所示:

Lorem Lorem Lorem 

然后他通过键入名称来指定要使用的图形。你知道吗

somefigure.png

如何使用python代码将其转换为.tex:

Lorem Lorem Lorem 

\begin{figure}[H]

\includegraphics[scale=0.5]{somefigure}

\caption{somefigure}

\end{figure}

难点在于检测名称并将其扩展为latex格式。你知道吗

我试过:

with open("INTRODUCTION.txt") as INTRODUCTIONTXT:
    with open("INTRODUCTION.tex", "w") as INTRODUCTIONTEX:
        for lines in INTRODUCTIONTXT:
        INTRODUCTIONTEX.write(lines)


INTROFIG = open("INTRODUCTION.txt")
if "PNP.name.PNP" in INTROFIG:

print("\begin{figure}[H]\n\centering") 

如果你能回答我,我将不胜感激!你知道吗


Tags: 代码用户txt名称内容with数字open
1条回答
网友
1楼 · 发布于 2024-09-30 00:38:22

希望这个未经测试的代码能满足您的需求

filename = 'INTRODUCTION'

# This is a raw (note the r - ignores \ escapes) multiline string.
# The {{ and }} become { and } and {0} will be replaced by the first argument
# of the format method.
figure_block = r'''\begin{{figure}}[H]

\includegraphics[scale=0.5]{{{0}}}

\caption{{{0}}}

\end{{figure}}

'''

with open(filename + '.txt') as txtfile:
    with open(filename + '.tex', 'w') as texfile:
        for line in txtfile:
            stripped_line = line.strip()  # remove white-space either side
            if stripped_line.endswith('.png'):  # self-explanatory   yay python
                 texfile.write(figure_block.format(stripped_line))
            else:
                 texfile.write(line)

相关问题 更多 >

    热门问题