다음과 같이 로마 숫자를 사용하여 시의 연을 순차적으로 번호를 매길 수 있습니다.
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
따라서 다른 관점에서 보면 이는 생성된 로마 숫자 목록에서 항목을 선택하고 해당 항목을 모든 섹션의 마지막 섹션에 정렬하는 것일 수 있습니다.
답변1
각 블록 뒤의 새 줄에 레코드 번호를 인쇄하는 것이 더 간단할 수 있습니다. 빈 줄이 완전히 비어 있는 경우(즉, 비어 있지 않은 경우 \n\n
) AWK의 "단락 모드"를 사용할 수 있습니다 \n \n
(빈 문자열은 다음과 같습니다).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 ")"
확인할 수 있습니다 . 주어진 십진수에 대해 로마 숫자를 생성해 보세요. 1000개의 배치마다 "M"을 반복합니다.d2r()
d2r()
블록의 마지막 줄과 같은 줄에 숫자를 인쇄하려면 원래 들여쓰기를 유지하는 방법과 여백의 사용 가능한 공간이 필요한 공간보다 적을 때 어떻게 해야 하는지 알아내야 합니다. 번호를 인쇄하세요.
POSIX awk를 사용하여 위의 내용을 OP 예제에 적용하려면 다음과 같습니다.
$ 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."
답변2
다음 Perl 스크립트는 Perl을 사용합니다.로마기준 치수. 사용 중인 UNIX 유형에 따라 운영 체제에 맞게 사전 패키지되어 있을 수 있습니다. 예를 들어 Debian 및 Ubuntu 또는 Mint와 같은 파생 제품에서는 sudo apt-get install libroman-perl
. 그렇지 않으면 다음 명령을 사용하여 설치하십시오 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
function을 roman()
function과 함께 사용합니다. 즉, 교체합니다.두번째줄에는 다음이 포함됩니다 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];
답변3
사용행복하다(이전 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
아래 설명된 것처럼 인접한 섹션 사이의 다양한 간격을 수용하도록 코드를 조정할 수 있습니다.
간단히 말해서, 시 파일은 1) 줄 시작, 2) 가로 간격 7개, 3) 줄 바꿈 패턴을 찾는 정규식을 사용하여 slurp
단락에 삽입 됩니다. split
[섹션을 구분하는 줄이 실제로 비어 있는 경우 정규식으로 사용됩니다.] 이 함수는 매개변수/부사를 통해 빈 문자열을 제거하고 4개의 단락(예: 섹션)을 남기도록 지시됩니다. 단락에는 키 값으로 번호가 매겨져 있으며 먼저 루프에 전달된 다음 중첩 루프에 전달됩니다. 중첩 루프에서 값(즉, 텍스트)은 (8)로 나누어지고 0에서 7까지 번호가 매겨집니다(아래에서 각 섹션의 번호를 매기는 데 사용됨).@para
/^^ \h**7 "\n" /
^^
\h**7
\n
/^^ $$ "\n" /
split
:skip-empty
kv
for
for
for
$v
lines
kv
인쇄는 단락 번호를 문자열로 포맷한 다음 (텍스트) 문자열을 put
호출 하여 수행됩니다 . 문자열은 를 통해 연결됩니다 . 단락 번호 매기기는 요소가 3개인 최소 너비(오른쪽 맞춤) 문자열 형식 지정 도구인 를 사용하여 수행됩니다 . 조건은 단락의 일곱 번째 줄(색인 0) 에만 번호가 매겨져 있습니다 . 들여쓰기는 으로 하기 때문에 출력이 제대로 정렬되도록 시의 각 줄을 다듬어야 합니다 .sprintf
$k+1
$l_value
~
sprintf( "%*s ", 5, "{to-roman($k+1) if $l_key == 7}")
if
$l_key == 7
sprintf
$l_value
trim-leading
마지막으로 서브루틴은 명령줄에서 호출된 모듈을 사용하여 단락 카운터를 로마 숫자로 to-roman(…)
변환합니다 . $k+1
[사실 접미사는 여기서도 작동합니다]. Raku 모듈은 다음에서 검색할 수 있습니다.Math::Roman
-M
(…)R
https://modules.raku.org설치하고 zef
다음을 참조하세요.https://github.com/ugexe/zef.
인용하다:
https://modules.raku.org/dist/Math::Roman:cpan:TITSUKI
https://raku.org