搜索并移动对内联引用的引用

2024-06-16 18:30:36 发布

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

我正在导出一个Google文档并用https://github.com/facundoolano/googledoc2latex转换它。(这是迄今为止我发现的最准确、最免费的工具)

文档中的脚注(如html版本)位于文本下方

[text]
This is an example.$^{[1]}$ I like it.$^{[2]}$
[text]
[1] I'm a footnote!
[2] I'm also a footnote!

预期的结果应该是

[text]
This is an example.\footnote{I'm a footnote!} I like it.\footnote{I'm also a footnote!}
[text]

就我而言,可以使用awk、sed、perl、python、bash。。。从长远来看,python将非常棒,因为它可以合并到项目中

因此脚本需要找到所有引用并用真实文本替换它们

我没有找到开始使用sed和awk的方法,也没有使用perl和python的经验。有什么建议吗


Tags: text文档文本anisexamplegoogleit
2条回答

Perl代码算法

  • 用正则表达式将文本与脚注分开
  • 替换每个脚注
use strict;
use warnings;
use feature 'say';

my $text;
my %footnote;

/^\[(\d+)\] (.*)\Z/ ? $footnote{$1} = $2 : ($text .= $_) while <DATA>;

$text =~ s/\$\^\{\[$_\]\}\$/\\footnote{$footnote{$_}}/g for keys %footnote;

say $text;

__DATA__
[text]
This is an example.$^{[1]}$ I like it.$^{[2]}$
[text]
[1] I'm a footnote!
[2] I'm also a footnote!

输出

[text]
This is an example.\footnote{I'm a footnote!} I like it.\footnote{I'm also a footnote!}
[text]

Perl解决方案:

perl -ne '
    if (/^(\[[0-9]+\]) (.*)/) {
        $f{$1} = $2;
    } else { 
        push @lines, $_;
    }
    END {
        print s{\$\^\{(\[[0-9]+\])\}\$}{$f{$1} // "Missing $1!!!"}ger
            for @lines }
'   file.txt
  • -n逐行读取输入
  • 第一个正则表达式匹配脚注的定义,它将文本存储到[1][2]等键下的散列%f
  • 不包含脚注定义的行存储在@lines数组中
  • 读取文件后,将打印存储的行。在每一行上,脚注的引用都被存储在散列中的值替换,如果没有找到定义,则替换为Missing [4]

相关问题 更多 >