Perl 如何从大型文本文件中删除停止字?

Perl 如何从大型文本文件中删除停止字?,perl,stop-words,Perl,Stop Words,我有一个十亿字的语料库,我收集了一个标量。我有一个.regex文件,其中包含我想从数据(文本)中删除的所有停止字 我不知道如何使用这个.regex文件,所以我制作了一个数组,并将.regex文件的所有停止字存储在我的停止字数组中 要删除停止词,请执行以下操作: grep { $scalarText =~ s/\b\Q$_\E\b/ /g } @stopList; chomp(@stopwords = `cat foo.regex`); # if each stopword is an ind

我有一个十亿字的语料库,我收集了一个标量。我有一个.regex文件,其中包含我想从数据(文本)中删除的所有停止字

我不知道如何使用这个.regex文件,所以我制作了一个数组,并将.regex文件的所有停止字存储在我的停止字数组中

要删除停止词,请执行以下操作:

grep { $scalarText =~ s/\b\Q$_\E\b/ /g } @stopList;
chomp(@stopwords = `cat foo.regex`);

# if each stopword is an independent regex:
$stopword_string = join "|" => @stopwords;

# else if each stopword is a literal
$stopword_string = join "|" => map {quotemeta} @stopwords;

# now compile it (maybe add some qr//OPTS)
$stopword_rx     = qr/\b(?:$stopword_string)\b/;

这需要很长时间才能执行。如何在Perl脚本中使用.regex文件删除停止字?或者有没有更快的方法删除停止词?

您可能想使用它将Perl正则表达式列表编译成一个正则表达式。

我找到了一种更快的方法。节省了我大约4秒钟的时间

my $qrstring = '\b(' . (join '|', @stopList) . ')\b';
$scalarText =~ s/$qrstring/ /g;
其中
stopList
是我所有单词的数组 而
scalarText
是我的全部文本


如果你知道的话,有谁能告诉我一个更快的方法吗?

是的,我想你在那里做的非常慢,尽管有几个原因。我认为,在从语料库中构建包含10亿个单词的字符串之前,需要先处理stopwords正则表达式

我不知道.regex文件是什么,但我假设它包含一个合法的Perl正则表达式,您只需使用以下方法即可编译:

$stopword_string = `cat foo.regex`;
$stopword_rx     = qr/$stopword_string/;
这可能假定在开始时有一个
(?x)

但如果stopword文件是一个行列表,则需要执行以下操作:

grep { $scalarText =~ s/\b\Q$_\E\b/ /g } @stopList;
chomp(@stopwords = `cat foo.regex`);

# if each stopword is an independent regex:
$stopword_string = join "|" => @stopwords;

# else if each stopword is a literal
$stopword_string = join "|" => map {quotemeta} @stopwords;

# now compile it (maybe add some qr//OPTS)
$stopword_rx     = qr/\b(?:$stopword_string)\b/;
警告
小心使用
\b
:如果第一个单词中的第一个字符和最后一个单词中的最后一个字符是alphanumunder(一个
\w
字符),它只会执行上面所说的操作。否则,它将断言一些你可能不想说的东西。如果可能的话,你需要更具体一些。前导的
\b
需要变成
(?:)(?请祈祷没有一个停止字包含正则表达式中有意义的字符:您没有使用
\Q\E
,所以可能会发生不好的事情,不要将停止字保存到一个组中(
$1
):这需要花费时间和内存。只使用集群(即,不捕获)通过
(?:xxx)
进行分组,就像我在回答中所做的那样。相对于什么?相对于我之前需要做的时间,节省了4秒,大约73秒seconds@DaveSherohman:除非你有太多的选择,以至于优化没有被使用(很多),5.10+中用于|-d固定字符串的内置aho corasick匹配将大大优于Regexp::Assembly或半打类似模块中的任何一个。由于最近的trie优化,模块在减少带有冗余部分的常见模式方面所做的一些技巧将自动为您解决。Perl automatically将所需的技巧应用于一组选项之间具有公共常量字符串的备选方案。使用
-Mre=debug
查看此操作。阅读提示:任何理智的人都不应该使用
$arg=`cat file`
,他们应该使用
$arg=file::Slurp::Slurp($file)
或类似的方法。