为了在毕业设计中敲出好看的、和顶会论文类似的伪代码块,我毅然决然地决定使用latex,但其语法比起word太过复杂,我就想着有没有什么办法能在word中嵌入latex代码,果不其然真有对应的word插件!

图片

首先是安装latex:

https://zhuanlan.zhihu.com/p/617431548 LaTex 安装(2023最新版+Windows)

安装word插件:

https://www.neusncp.com/user/blog?id=151 如何在Word中优雅地插入伪代码

这里我跟随博客的脚步使用了 texsword.0.8,这个插件上次更新已经是很久很久了…

在这里最困扰我的是无法使用中文,一些在博客上所说明的使用中文的方法在texstudio上可以随意使用,但在插件上就不生效了。

https://blog.csdn.net/z_feng12489/article/details/90449495 LaTex支持中文的三种方式

报的错误显示用utf8格式无法解码对应字符,这里我猜测是word上对应编辑器使用了Unicode格式(也有可能是别的格式)的中文字符,所以导致中文无法解码,同时该插件没有对应的修改字符格式的选项。

于是我就想latex肯定也能像编程语言能读取外部文件,只需要在外部文件的编辑器上输入中文部分,在此编辑器上更改编码格式为utf8不就行了,没想到这个方法还真管用。

1
2
3
4
5
6
7
8
9
10
11
12
\documentclass{article}
\usepackage{CJKutf8}
%只能加载这个包才生效 不能用ctex 原理未知
%\usepackage[UTF8]{ctex}
\usepackage{algorithm}
\usepackage{algpseudocode}
\renewcommand{\thealgorithm}{}
\begin{document}
\begin{CJK}{UTF8}{gbsn}
\input{/Users/123456/Desktop/system/algorithm2.1.tex}
\end{CJK}
\end{document}

在/Users/123456/Desktop/system/algorithm2.1.tex中对应伪代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
\floatname{algorithm}{算法2.1}
\begin{algorithm}
\caption{Federated Averaging (FedAvg算法)}
\begin{algorithmic}
\Require
\State 输入:通信次数$T$,客户端数量$C$,本地训练批次大小$B$,训练轮数$E$,学习率$\eta$,初始化模型参数 $w_0$
\State 输出:聚合后的下一轮全局模型参数$w_{t+1}$
\Ensure
\Function{main}{$w_{T+1},T,C,E,\eta$}
\State Global model $w_{T+1}$
\For{each round $t = 1, 2, \dots, T$}
\State $m \leftarrow \max(C \cdot K, 1)$
\State $S_t \leftarrow$ (random set of $m$ clients)
\For{each client $k \in S_t$ \textbf{in parallel}}
\State $w_{t+1}^k \leftarrow$ ClientUpdate($k, w_t$)
\EndFor
\State $w_{t+1} \leftarrow \sum_{k=1}^m \frac{n_k}{n} w_{t+1}^k$
\EndFor
\State \textbf{return} $w_{T+1}$
\EndFunction
\Function{ClientUpdate}{$k, w$}
\State $B \leftarrow$ (split $P_k$ into batches of size $B$)
\For{each local epoch $i$ from 1 to $E$}
\For{batch $b \in B$}
\State $w \leftarrow w - \eta \nabla \ell(w; b)$
\EndFor
\EndFor
\State \textbf{return} $w$
\EndFunction
\end{algorithmic}
\end{algorithm}

结果就能正常编译生成伪代码块了!可喜可贺可喜可贺

图片