주간 챌린지 #081 태스크 #2::라쿠

작업 #2 › 빈도 정렬



You are given file named "input".

Write a script to find the frequency of all the words.

It should print the result as first column of each line should be
the frequency of the the word followed by all the words of that
frequency arranged in lexicographical order. Also sort the words in 
the ascending order of frequency.

INPUT 파일은 다음과 같습니다.

웨스트 사이드 스토리

고전 로맨틱 비극 "로미오와 줄리엣"의 수상 경력에 빛나는 각색. 불화하는 가족은 두 개의 전쟁을 벌이는 뉴욕시 갱, Riff가 이끄는 백인 Jets와 Bernardo가 이끄는 Latino Sharks가 됩니다. 그들의 증오는 어느 쪽도 어떤 형태의 이해와도 공존할 수 없는 지경에 이른다. 그러나 리프의 가장 친한 친구이자 전 제트기였던 토니와 베르나르도의 여동생 마리아가 댄스 파티에서 만나자 아무도 그들의 사랑을 막을 수 없습니다. 마리아와 토니는 도주할 계획으로 비밀리에 만나기 시작한다. 그런 다음 Sharks와 Jets는 고속도로 아래에서 소란을 일으킬 계획을 세웁니다. 마리아는 폭력이 끝날 수 있기를 바라면서 토니를 보내 그것을 멈추게 합니다. 그것은 끔찍하게 잘못되었고, 연인들이 무슨 일이 일어났는지 알기도 전에 비극이 닥치며 절정에 달하는 가슴 아픈 결말까지 멈추지 않습니다.

NOTE

For the sake of this task, please ignore the following in the input file:

. " ( ) , 's --



OUTPUT

1 But City It Jet Juliet Latino New Romeo Side Story Their Then 
West York adaptation any anything at award-winning away become 
before begin best classic climactic coexist control dance do 
doesn't end ending escalates families feuding form former friend 
gains gangs goes happened hatred heartbreaking highway hoping in
know love lovers meet meeting neither no one plan planning point 
romantic rumble run secret sends sister streets strikes terribly 
their two under understanding until violence warring what when 
where white whoever wins with wrong younger
2 Bernardo Jets Riff Sharks The by it led tragedy
3 Maria Tony a can of stop
4 to
9 and the

Raku에서 파일 읽기



Raku에서 파일을 읽는 것은 정말 쉽고 간단합니다.
이 작업은 읽고자 하는 파일 이름이 이미 "입력"임을 나타냅니다.

sub MAIN {
    if "input".IO.r.not {
        die "`input' is not readable";
    }
}

이 예제는 "입력"파일 경로를 읽을 수 있는지 테스트하거나 "또는"을 사용하여 더 짧게 작성할 수 있는 오류(또는 예외?)를 발생시키는 방법을 보여줍니다.

    "input".IO.r or die "`input' is not readable";
    # or ...
    die "`nope!" if "input".IO.r.not;
    # or ...
    die "`I said nope!" unless "input".IO.r;

Raku는 또한 그렇게 쓰고 싶다면 더 자연스러운 언어로 들립니다. (하지만 이것은 취향일 뿐입니다.)

".r"과 같은 일부 서브루틴은 작업을 더 쉽게 만들어줍니다.
".lines"및 ".words"

for "input".IO.lines -> line-number, line-string {
    say "$line-number: line-string";
}

이 작업에서는 물론 ".words"를 사용할 수 있습니다.

내가 감동한 것은 다음 단계입니다.

가방



Raku는 모국어로 제공합니다. "예, 해시를 가방으로 사용할 수 있습니다."하지만 이렇게 하면 작업이 명확하고 즐겁게 보입니다.

> raku -e '"yes, we can use a hash as a bag".words.Bag.raku.say'
("hash"=>1,"as"=>1,"we"=>1,"use"=>1,"bag"=>1,"yes,"=>1,"can"=>1,"a"=>2).Bag

각 값은 단어의 빈도를 나타냅니다.
(참고: '-e' 옵션을 사용하여 하나의 라이너 프로그램을 실행할 수 있습니다)

이제 빈도에 따라 정렬할 수 있도록 키와 값을 반전해야 할 수도 있습니다.

sub MAIN {
    my $in = "input".IO;
    $in.r or die "no!" x 5;

    my %r;
    for bag($in.words) -> $as-pair {
        say "will change to {$as-pair.value} => {$as-pair.key}";
    }
}



shell> raku ch-2.raku | head
will change to 1 => planning
will change to 1 => end
will change to 2 => it
will change to 1 => run
will change to 1 => warring
will change to 3 => stop
will change to 1 => award-winning
will change to 1 => City
will change to 1 => York
will change to 1 => happened

".invert"이 있지만 여기서는 필요하지 않다고 생각합니다.

결과를 해시 변수로 저장하겠습니다.

sub MAIN {
    my $in = "input".IO;
    $in.r or die "no!" x 5;

    my %r;
    %r{.value}.push(.key) for bag($in.words);
}

.map을 사용할 수 있지만 .map은 전혀 사용하지 않더라도 항상 무언가를 반환하므로 for가 더 나은 선택입니다.

종류



가지고 있기 때문에 정렬이 쉽습니다 sort

sub MAIN {
    my $in = "input".IO;
    $in.r or die "no!" x 5;

    my %r;
    %r{.value}.push(.key) for bag($in.words);
    %r.sort.put;
}

작업을 끝내려고 했으나 사전순으로 단어가 필요하므로 ...

sub MAIN {
    my $in = "input".IO;
    $in.r or die "no!" x 5;

    my %r;
    %r{.value}.push(.key) for bag($in.words);
    for %r -> $as-pair {
        %r{$as-pair.key} = sort %r{$as-pair.key}
    }
    %r.sort.join("\n").put;
}

이 정도면 충분합니다. 😎 가방을 만들고 분류하는 방법에 집중하기 위해 필터링 단어는 건너뜁니다.

최종 코드



더 많은 단축키를 사용하기 때문에 최종 코드는 항상 다릅니다.

with "input".IO {
    .r or die "no `input' file";
    my %r;
    %r{.value}.push(.key).=sort
        for bag(.words>>.subst(/"'s"||<[\W]-[-]>||"--"/,'',:g));
    %r.sort.join("\n").put;
}

그러나 나는 여기에 약간의 참조를 남깁니다. 🧐
with
Regex
subst
>>

읽어 주셔서 감사합니다!
https://perlweeklychallenge.org/을 방문하여 관심이 있는 경우 코드를 제공하십시오~!! 🙏

좋은 웹페이지 즐겨찾기