如何计算单词对并输出文件

发布于 2025-02-06 12:57:51 字数 400 浏览 1 评论 0原文

my $line = "The quick brown fox jumps over the lazy dog.";

while ($line =~ /(\w+)\s(?=(\w+\b))/g) {
    print("$1 $2\n");
}

**到目前为止,这将输出 快速 快速棕色 Brown Fox ....

是否可以输出一个文本文件,例如: 快速:3(发生的时间) 快速棕色:2 布朗·福克斯(Brown Fox):5 ...

也许我们可以使用类似的东西

$wordcount{$word} += 1;

,但是当然,任何合理的解决方案都受到欢迎,非常感谢你们。 PS为模糊的表达道歉,因为我是一个超级初学者。

**

my $line = "The quick brown fox jumps over the lazy dog.";

while ($line =~ /(\w+)\s(?=(\w+\b))/g) {
    print("$1 $2\n");
}

**So far this will output
The quick
quick brown
brown fox....

Is there a way to output a text file that also includes word count for example:
The quick: 3 (times of occurrence)
quick brown:2
brown fox:5...

Maybe we can use something like

$wordcount{$word} += 1;

but of course any plausible solutions are welcomed and thank you guys very much. P.S. apologies for the vague expression since I am a super beginner.

**

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落墨 2025-02-13 12:57:51

您可以使用将单词对(键)映射到出现数量(值)的哈希。

示例:

#!/bin/perl
use strict;
use warnings;

my $line = "The quick brown fox jumps over the lazy dog.";

my %paircount;
while ($line =~ /(\w+)\s+(?=(\w+\b))/g) {
    # put the word pair in the map and increase the count
    $paircount{"$1 $2"}++;
}

# print the result
while(my($key, $value) = each %paircount) {
    print "$key : $value time(s)\n";
}

可能的输出:

fox jumps : 1 time(s)
lazy dog : 1 time(s)
over the : 1 time(s)
the lazy : 1 time(s)
brown fox : 1 time(s)
jumps over : 1 time(s)
quick brown : 1 time(s)
The quick : 1 time(s)

You could use a hash that maps the word pair (key) to the number of occurrences (value).

Example:

#!/bin/perl
use strict;
use warnings;

my $line = "The quick brown fox jumps over the lazy dog.";

my %paircount;
while ($line =~ /(\w+)\s+(?=(\w+\b))/g) {
    # put the word pair in the map and increase the count
    $paircount{"$1 $2"}++;
}

# print the result
while(my($key, $value) = each %paircount) {
    print "$key : $value time(s)\n";
}

Possible output:

fox jumps : 1 time(s)
lazy dog : 1 time(s)
over the : 1 time(s)
the lazy : 1 time(s)
brown fox : 1 time(s)
jumps over : 1 time(s)
quick brown : 1 time(s)
The quick : 1 time(s)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文