AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / unix / 问题 / 681499
Accepted
Dingo
Dingo
Asked: 2021-12-15 17:19:01 +0800 CST2021-12-15 17:19:01 +0800 CST 2021-12-15 17:19:01 +0800 CST

用罗马数字给诗节编号

  • 772

我可以使用这样的罗马数字按顺序编号一首诗的任何节:

       
       Injurious love, why still to mar accord
       Between desires has been thy favourite feat?
       Why does it please thee so, perfidious lord,
       Two hearts should with a different measure beat?
       Thou wilt not let me take the certain ford,
       Dragging me where the stream is deep and fleet.
       Her I abandon who my love desires,
       While she who hates, respect and love inspires.
       
       Thou to Rinaldo show'st the damsel fair,
       While he seems hideous to that gentle dame;
       And he, who when the lady's pride and care,
       Paid back with deepest hate her amorous flame,
       Now pines, himself, the victim of despair,
       Scorned in his turn, and his reward the same.
       By the changed damsel in such sort abhorred,
       She would choose death before that hated lord.
       
       He to the Pagan cries: "Forego thy theft,
       And down, false felon, from that pilfer'd steed;
       I am not wont to let my own be reft.
       And he who seeks it dearly pays the deed.
       More -- I shall take from thee yon lovely weft;
       To leave thee such a prize were foul misdeed;
       And horse and maid, whose worth outstrips belief,
       Were ill, methinks, relinquished to a thief."
       
       "Thou liest," the haughty Saracen retorts,
       As proud, and burning with as fierce a flame,
       "A thief thyself, if Fame the truth reports:
       But let good deeds decide our dubious claim,
       With whom the steed or damsel fair assorts:
       Best proved by valiant deeds: though, for the dame,
       That nothing is so precious, I with thee
       (Search the wide world throughout) may well agree."
        

进入这个:罗马大写数字与最后一节对齐?

       Injurious love, why still to mar accord
       Between desires has been thy favourite feat?
       Why does it please thee so, perfidious lord,
       Two hearts should with a different measure beat?
       Thou wilt not let me take the certain ford,
       Dragging me where the stream is deep and fleet.
       Her I abandon who my love desires,
I      While she who hates, respect and love inspires.
       
       Thou to Rinaldo show'st the damsel fair,
       While he seems hideous to that gentle dame;
       And he, who when the lady's pride and care,
       Paid back with deepest hate her amorous flame,
       Now pines, himself, the victim of despair,
       Scorned in his turn, and his reward the same.
       By the changed damsel in such sort abhorred,
II     She would choose death before that hated lord.
       
       He to the Pagan cries: "Forego thy theft,
       And down, false felon, from that pilfer'd steed;
       I am not wont to let my own be reft.
       And he who seeks it dearly pays the deed.
       More -- I shall take from thee yon lovely weft;
       To leave thee such a prize were foul misdeed;
       And horse and maid, whose worth outstrips belief,
III    Were ill, methinks, relinquished to a thief."
       
       "Thou liest," the haughty Saracen retorts,
       As proud, and burning with as fierce a flame,
       "A thief thyself, if Fame the truth reports:
       But let good deeds decide our dubious claim,
       With whom the steed or damsel fair assorts:
       Best proved by valiant deeds: though, for the dame,
       That nothing is so precious, I with thee
IV     (Search the wide world throughout) may well agree."
        

我想知道是否有任何方法可以使用文本实用程序在 linux 中进行此操作。它可能不适合 awk,以罗马风格生成数字,但我已经在互联网上的某个地方找到了一个 bash 脚本来生成罗马数字

#/bin/bash
# roman.sh
#
#   Function
#
    num2roman() { # NUM
    # Returns NUM in roman letters
    #
        input=$1    # input num
        output=""   # Clear output string
        len=${#input}   # Initial length to count down
        
        roman_val() { # NUM one five ten
        # This sub does the basic 'roman' algorythm
        #
            N=$1
            one=$2
            five=$3
            ten=$4
            out=""
            
            case $N in
            0)  out+="" ;;
            [123])  while [[ $N -gt 0 ]]
                do  out+="$one"
                    N=$(($N-1))
                done
                ;;
            4)  out+="$one$five"    ;;
            5)  out+="$five"    ;;
            [678])  out+="$five"
                N=$(($N-5))
                while [[ $N -gt 0 ]]
                do  out+="$one"
                    N=$(($N-1))
                done
                ;;
            9)  while [[ $N -lt 10 ]]
                do  out+="$one"
                    N=$(($N+1))
                done
                out+="$ten"
                ;;
            esac
            echo $out
        }
        
        while [[ $len -gt 0  ]]
        do  # There are letters to add
            num=${input:0:1}
            # Do action according position
            case $len in
            1)  # 1
                output+="$(roman_val $num I V X)"
                ;;
            2)  # 10
                output+="$(roman_val $num X L C)"
                ;;
            3)  # 100
                output+="$(roman_val $num C D M)"
                ;;
            *)  # 1000+
                # 10'000 gets a line above, 100'000 gets a line on the left.. how to?
                num=${input:0:(-3)}
                while [[ $num -gt 0 ]]
                do  output+="M"
                    num=$(($num-1))
                done
                
                ;;
            esac
            input=${input:1} ; len=${#input}
        done
        echo $output
    }
#
#   Call it
#
    num2roman $1

我用这种语法调用:

 for N in `seq 1 10`;do ./roman.sh $N; done

谁的输出是:

I
II
III
IV
V
VI
VII
VIII
IX
X

因此,从另一个角度来看,这可能只是从生成的罗马数字列表中挑选任何项目,然后将其中任何一项与任何一节的最后一节对齐

text-processing text-formatting
  • 3 3 个回答
  • 282 Views

3 个回答

  • Voted
  1. Best Answer
    rowboat
    2021-12-16T01:23:34+08:002021-12-16T01:23:34+08:00

    在每个块之后的新行上打印记录号可能更简单。如果您的空白行完全空白(即它们是\n\n而不是\n \n),则可以使用 AWK 的“段落模式”(空字符串为RS):

    function d2r(n,    m) {
        m = sprintf("%*s", int(n/1000), "")
        gsub(/ /, "M", m)
        return m r100[int(n%1000/100)] r10[int(n%100/10)] r1[int(n%10)]
    }
    
    BEGIN {
        split("C,CC,CCC,CD,D,DC,DCC,DCCC,CM", r100, ",")
        split("X,XX,XXX,XL,L,LX,LXX,LXXX,XC", r10, ",")
        split("I,II,III,IV,V,VI,VII,VIII,IX", r1, ",")
    
        RS = ""
    }
    
    {
        print
        print d2r(NR) " (" NR ")"
        print ""
    }
    

    以上另存为roman_numeral_blocks.awk

    $ printf '%s\n\n' foo bar | awk -f roman_numeral_blocks.awk
    foo
    I (1) 
    
    bar
    II (2) 
    
    

    该" (" NR ")"部分是为了让您可以验证d2r()产生了正确的结果。d2r()尝试为给定的十进制数生成罗马数字。每 1000 手都简单地重复“M”。

    如果您希望将数字打印在与块的最后一行相同的行上,那么您必须弄清楚如何保留原始缩进,以及当页边空白中的可用空间小于所需空间时该怎么办打印号码。

    要将上述内容应用于 OPs 示例,使用任何 POSIX awk,将是:

    $ cat roman_numeral_blocks.awk
    function d2r(n,    m) {
        m = sprintf("%*s", int(n/1000), "")
        gsub(/ /, "M", m)
        return m r100[int(n%1000/100)] r10[int(n%100/10)] r1[int(n%10)]
    }
    
    BEGIN {
        split("C,CC,CCC,CD,D,DC,DCC,DCCC,CM", r100, ",")
        split("X,XX,XXX,XL,L,LX,LXX,LXXX,XC", r10, ",")
        split("I,II,III,IV,V,VI,VII,VIII,IX", r1, ",")
    }
    
    NR > 1 { prt(0) }
    { prev = $0 }
    END { prt(1) }
    
    function prt(isEnd,     pfx) {
        if ( (!NF || isEnd) && (match(prev, /[^[:space:]]/)) ) {
            prev = substr(prev, RSTART)
            pfx = sprintf("%-*s", RSTART-1, d2r(++numParas) " ")
        }
        print pfx prev
    }
    

    $ awk -f roman_numeral_blocks.awk file
    
           Injurious love, why still to mar accord
           Between desires has been thy favourite feat?
           Why does it please thee so, perfidious lord,
           Two hearts should with a different measure beat?
           Thou wilt not let me take the certain ford,
           Dragging me where the stream is deep and fleet.
           Her I abandon who my love desires,
    I      While she who hates, respect and love inspires.
    
           Thou to Rinaldo show'st the damsel fair,
           While he seems hideous to that gentle dame;
           And he, who when the lady's pride and care,
           Paid back with deepest hate her amorous flame,
           Now pines, himself, the victim of despair,
           Scorned in his turn, and his reward the same.
           By the changed damsel in such sort abhorred,
    II     She would choose death before that hated lord.
    
           He to the Pagan cries: "Forego thy theft,
           And down, false felon, from that pilfer'd steed;
           I am not wont to let my own be reft.
           And he who seeks it dearly pays the deed.
           More -- I shall take from thee yon lovely weft;
           To leave thee such a prize were foul misdeed;
           And horse and maid, whose worth outstrips belief,
    III    Were ill, methinks, relinquished to a thief."
    
           "Thou liest," the haughty Saracen retorts,
           As proud, and burning with as fierce a flame,
           "A thief thyself, if Fame the truth reports:
           But let good deeds decide our dubious claim,
           With whom the steed or damsel fair assorts:
           Best proved by valiant deeds: though, for the dame,
           That nothing is so precious, I with thee
    IV     (Search the wide world throughout) may well agree."
    
    • 3
  2. cas
    2021-12-16T01:46:17+08:002021-12-16T01:46:17+08:00

    以下 perl 脚本使用 perl Roman模块。根据您使用的 unix 类型,这可能会为您的操作系统预先打包。例如,在 Debian 和 Ubuntu 或 Mint 等衍生产品上,您可以使用sudo apt-get install libroman-perl. 其他 Linux 发行版可能具有类似名称的软件包。否则,安装它cpan:

    $ perl -MRoman -00 -ne '
        @para = split /\n/, $_;
        foreach my $l (0..$#para-1) {
          $para[$l] = sprintf "%6s  %s", "", $para[$l]
        };
    
        $para[$#para] = sprintf "%6s  %s", roman(++$stanza), $para[$#para];
    
        print join("\n", @para),"\n\n"' poem2.txt 
            Injurious love, why still to mar accord
            Between desires has been thy favourite feat?
            Why does it please thee so, perfidious lord,
            Two hearts should with a different measure beat?
            Thou wilt not let me take the certain ford,
            Dragging me where the stream is deep and fleet.
            Her I abandon who my love desires,
         i  While she who hates, respect and love inspires.
    
            Thou to Rinaldo show'st the damsel fair,
            While he seems hideous to that gentle dame;
            And he, who when the lady's pride and care,
            Paid back with deepest hate her amorous flame,
            Now pines, himself, the victim of despair,
            Scorned in his turn, and his reward the same.
            By the changed damsel in such sort abhorred,
        ii  She would choose death before that hated lord.
    
            He to the Pagan cries: "Forego thy theft,
            And down, false felon, from that pilfer'd steed;
            I am not wont to let my own be reft.
            And he who seeks it dearly pays the deed.
            More -- I shall take from thee yon lovely weft;
            To leave thee such a prize were foul misdeed;
            And horse and maid, whose worth outstrips belief,
       iii  Were ill, methinks, relinquished to a thief."
    
            "Thou liest," the haughty Saracen retorts,
            As proud, and burning with as fierce a flame,
            "A thief thyself, if Fame the truth reports:
            But let good deeds decide our dubious claim,
            With whom the steed or damsel fair assorts:
            Best proved by valiant deeds: though, for the dame,
            That nothing is so precious, I with thee
        iv  (Search the wide world throughout) may well agree."
    
    

    这以段落模式读取文件(段落边界是一个或多个空行),将每个段落拆分为一个数组 ( @para),并将除最后一行之外的所有 @para 缩进 8 个空格。@para 的最后一行由一个 6 字符宽的罗马数字缩进,表示节号和另外两个空格。然后打印该数组。

    对于大写罗马数字,将uc函数与函数一起使用roman()- 即将包含以下内容的第二行替换为sprintf:

    $para[$#para] = sprintf "%6s  %s", uc(roman(++$stanza)), $para[$#para];
    

    如果您希望罗马数字左对齐,请使用%-6s. 例如

    $para[$#para] = sprintf "%-6s  %s", roman(++$stanza), $para[$#para];
    

    或者

    $para[$#para] = sprintf "%-6s  %s", uc(roman(++$stanza)), $para[$#para];
    
    • 1
  3. jubilatious1
    2021-12-21T16:24:55+08:002021-12-21T16:24:55+08:00

    使用Raku(以前称为 Perl_6)

    ~$ raku -MMath::Roman -e '
     my @para = .split( /^^ \h**7 "\n" /, :skip-empty ) given slurp;
     for @para.kv -> $k,$v { "\n".print; for $v.lines.kv -> $l_key,$l_value {
     put(sprintf( "%*s  ", 5, "{to-roman($k+1) if $l_key == 7}") ~ "{$l_value.trim-leading}")
     };};' Ariosto.txt
    

    示例输入(直接从上面的 OP 帖子中复制粘贴):

       Injurious love, why still to mar accord
       Between desires has been thy favourite feat?
       Why does it please thee so, perfidious lord,
       Two hearts should with a different measure beat?
       Thou wilt not let me take the certain ford,
       Dragging me where the stream is deep and fleet.
       Her I abandon who my love desires,
       While she who hates, respect and love inspires.
       
       Thou to Rinaldo show'st the damsel fair,
       While he seems hideous to that gentle dame;
       And he, who when the lady's pride and care,
       Paid back with deepest hate her amorous flame,
       Now pines, himself, the victim of despair,
       Scorned in his turn, and his reward the same.
       By the changed damsel in such sort abhorred,
       She would choose death before that hated lord.
       
       He to the Pagan cries: "Forego thy theft,
       And down, false felon, from that pilfer'd steed;
       I am not wont to let my own be reft.
       And he who seeks it dearly pays the deed.
       More -- I shall take from thee yon lovely weft;
       To leave thee such a prize were foul misdeed;
       And horse and maid, whose worth outstrips belief,
       Were ill, methinks, relinquished to a thief."
       
       "Thou liest," the haughty Saracen retorts,
       As proud, and burning with as fierce a flame,
       "A thief thyself, if Fame the truth reports:
       But let good deeds decide our dubious claim,
       With whom the steed or damsel fair assorts:
       Best proved by valiant deeds: though, for the dame,
       That nothing is so precious, I with thee
       (Search the wide world throughout) may well agree."
       
    

    样本输出:

           Injurious love, why still to mar accord
           Between desires has been thy favourite feat?
           Why does it please thee so, perfidious lord,
           Two hearts should with a different measure beat?
           Thou wilt not let me take the certain ford,
           Dragging me where the stream is deep and fleet.
           Her I abandon who my love desires,
        I  While she who hates, respect and love inspires.
    
           Thou to Rinaldo show'st the damsel fair,
           While he seems hideous to that gentle dame;
           And he, who when the lady's pride and care,
           Paid back with deepest hate her amorous flame,
           Now pines, himself, the victim of despair,
           Scorned in his turn, and his reward the same.
           By the changed damsel in such sort abhorred,
       II  She would choose death before that hated lord.
    
           He to the Pagan cries: "Forego thy theft,
           And down, false felon, from that pilfer'd steed;
           I am not wont to let my own be reft.
           And he who seeks it dearly pays the deed.
           More -- I shall take from thee yon lovely weft;
           To leave thee such a prize were foul misdeed;
           And horse and maid, whose worth outstrips belief,
      III  Were ill, methinks, relinquished to a thief."
    
           "Thou liest," the haughty Saracen retorts,
           As proud, and burning with as fierce a flame,
           "A thief thyself, if Fame the truth reports:
           But let good deeds decide our dubious claim,
           With whom the steed or damsel fair assorts:
           Best proved by valiant deeds: though, for the dame,
           That nothing is so precious, I with thee
       IV  (Search the wide world throughout) may well agree."
    

    上面的 Raku 代码对预先存在的缩进相当健壮,并且split可以调整代码以适应相邻节之间的不同间距,如下所述(如下)。

    Briefly, The poetry file is slurp-ed in and split into @para paragraphs using the /^^ \h**7 "\n" / regex, which looks for the pattern 1) ^^ start-of-line, 2) \h**7 seven horizontal whitespaces and 3) a \n newline. [If the lines separating stanzas are truly empty, use /^^ $$ "\n" / as the regex]. The split function is instructed to drop empty strings via the parameter/adverb :skip-empty, leaving 4 paragraphs (i.e stanzas). Paragraphs are numbered with kv key-value and first passed into a for loop, then passed into a nested for loop. Within the nested for loop the $v value (i.e. text) is broken into (8) lines, and numbered 0-to-7 with kv (used below for numbering each stanza).

    Printing is accomplished by put, which calls sprintf to format the $k+1 paragraph number as a string, followed by the$l_value (text) string. Strings are concatenated with ~. Paragraph numbering is accomplished using the three-element, minimum-width (right-justified) string formatter: sprintf( "%*s ", 5, "{to-roman($k+1) if $l_key == 7}"). The if conditional places numbering only on the $l_key == 7 (zero-indexed seventh) line of the paragraph. Since indentation accomplished with sprintf, each line of the $l_value poem needs to be trimmed using trim-leading, so that output aligns properly.

    Finally, the to-roman(…) sub converts the $k+1 paragraph counter to Roman Numeral, using the Math::Roman module called at the command-line with -M. [In fact, the postfix (…)R also works here]. Raku modules can be searched at https://modules.raku.org and installed with zef, see: https://github.com/ugexe/zef .

    References:
    https://modules.raku.org/dist/Math::Roman:cpan:TITSUKI
    https://raku.org

    • 1

相关问题

  • grep 从 $START 到 $END 的一组行并且在 $MIDDLE 中包含匹配项

  • 重新排列字母并比较两个单词

  • 在awk中的两行之间减去相同的列

  • 多行文件洗牌

  • 如何更改字符大小写(从小到大,反之亦然)?同时[重复]

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    模块 i915 可能缺少固件 /lib/firmware/i915/*

    • 3 个回答
  • Marko Smith

    无法获取 jessie backports 存储库

    • 4 个回答
  • Marko Smith

    如何将 GPG 私钥和公钥导出到文件

    • 4 个回答
  • Marko Smith

    我们如何运行存储在变量中的命令?

    • 5 个回答
  • Marko Smith

    如何配置 systemd-resolved 和 systemd-networkd 以使用本地 DNS 服务器来解析本地域和远程 DNS 服务器来解析远程域?

    • 3 个回答
  • Marko Smith

    dist-upgrade 后 Kali Linux 中的 apt-get update 错误 [重复]

    • 2 个回答
  • Marko Smith

    如何从 systemctl 服务日志中查看最新的 x 行

    • 5 个回答
  • Marko Smith

    Nano - 跳转到文件末尾

    • 8 个回答
  • Marko Smith

    grub 错误:你需要先加载内核

    • 4 个回答
  • Marko Smith

    如何下载软件包而不是使用 apt-get 命令安装它?

    • 7 个回答
  • Martin Hope
    user12345 无法获取 jessie backports 存储库 2019-03-27 04:39:28 +0800 CST
  • Martin Hope
    Carl 为什么大多数 systemd 示例都包含 WantedBy=multi-user.target? 2019-03-15 11:49:25 +0800 CST
  • Martin Hope
    rocky 如何将 GPG 私钥和公钥导出到文件 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Evan Carroll systemctl 状态显示:“状态:降级” 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim 我们如何运行存储在变量中的命令? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S 为什么 /dev/null 是一个文件?为什么它的功能不作为一个简单的程序来实现? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 如何从 systemctl 服务日志中查看最新的 x 行 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - 跳转到文件末尾 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla 为什么真假这么大? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis 在一个巨大的(70GB)、一行、文本文件中替换字符串 2017-12-30 06:58:33 +0800 CST

热门标签

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve