【问题标题】:Search for and move references to inline occurrence搜索并移动对内联引用的引用
【发布时间】:2020-12-13 13:47:36
【问题描述】:

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

Docs 中的脚注(与 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 的经验。有什么建议吗?

【问题讨论】:

  • Python 带有一个名为re 的正则表达式模块,它可以做到这一点。

标签: python perl awk sed replace


【解决方案1】:

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逐行读取输入
  • 第一个正则表达式匹配脚注的定义,它将文本存储在 %f 键下的哈希 [1][2] 等下。
  • 不包含脚注定义的行存储在@lines 数组中
  • 读取文件后,将打印存储的行。在每一行中,对脚注的引用将替换为存储在哈希中的值,如果未找到定义,则替换为 Missing [4]

【讨论】:

    【解决方案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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 2012-02-12
      • 2023-04-05
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多