【发布时间】: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”当作两个词,我宁愿把它算作一个