【问题标题】:Perl: Count number of times a word appears in text and print out surrounding wordsPerl:计算一个单词在文本中出现的次数并打印出周围的单词
【发布时间】:2014-08-15 15:18:18
【问题描述】:

我想做两件事:

1) 计算给定单词在文本文件中出现的次数

2) 打印出该词的上下文

这是我目前使用的代码:

my $word_delimiter = qr{
  [^[:alnum:][:space:]]*
  (?: [[:space:]]+ | -- | , | \. | \t | ^ )
  [^[:alnum:]]*
 }x;

my $word = "hello";
my $count = 0;

#
# here, a file's contents are loaded into $lines, code not shown
#

$lines =~ s/\R/ /g; # replace all line breaks with blanks (cannot just erase them, because this might connect words that should not be connected)
$lines =~ s/\s+/ /g; # replace all multiple whitespaces (incl. blanks, tabs, newlines) with single blanks
$lines = " ".$lines." "; # add a blank at beginning and end to ensure that first and last word can be found by regex pattern below

while ($lines =~ m/$word_delimiter$word$word_delimiter/g ) {
    ++$count;
    # here, I would like to print the word with some context around it (i.e. a few words before and after it)
}

三个问题:

1) 我的 $word_delimiter 模式是否能捕捉到所有可以用来分隔单词的合理字符?当然,我不想分隔连字符等。 [注意:我始终使用 UTF-8,但只使用英语和德语文本;而且我理解合理区分一个词可能是一个判断问题]

2) 当要分析的文件包含像“goodbye hello hello goodbye”这样的文本时,计数器只增加一次,因为正则表达式只匹配“hello”的第一次出现。毕竟,第二次它可以找到“你好”,它之前没有另一个空格。关于如何捕捉第二次出现的任何想法呢?我应该以某种方式重置 pos() 吗?

3) 如何(合理有效地)打印出匹配单词前后的几个单词?

谢谢!

【问题讨论】:

  • 有什么理由不使用\b 作为单词分隔符?
  • 其中一个问题是,如果我要搜索“jump”,我希望匹配“jump”,而不是“jumped”(有效)和“jump-西装”(不适用于 \b)
  • 另外,我把“you're”当作两个词,我宁愿把它算作一个

标签: string perl count


【解决方案1】:

1。我的$word_delimiter 模式是否能捕捉到所有可以用来分隔单词的合理字符?

  • 单词字符由字符类\w 表示。它还匹配来自非罗马文字的数字和字符。
  • \W 代表否定意义(非单词字符)。
  • \b 表示单词边界,长度为零。

使用这些已经可用的字符类就足够了。

2。关于如何捕捉第二次出现的任何想法?

使用零长度字边界。

while ( $lines =~ /\b$word\b/g ) {
    
    ++$count;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 2014-01-24
    • 1970-01-01
    • 2017-08-14
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多