gpt4 book ai didi

perl - 在语料库中标记单词

转载 作者:行者123 更新时间:2023-12-02 01:26:47 26 4
gpt4 key购买 nike

我是一名语言学家,使用 Perl 来帮助我组织数据,所以我一点也不精通,我的解决方案也不是很精简 :) 我今天的问题是,我想标记所有出现的项目例句语料库中的单词表。

我为另一个实验写了一个(草率的)脚本,但它只识别它找到的列表中的第一个单词,然后移动到下一个。我需要它来找到所有句子中的所有单词,最重要的是,在单词列表的第二列中分配一个标签。我的头脑无法解决如何做到这一点。帮助!

假设我的单词列表看起来像这样(一个制表符分隔的 .txt 文件,其中 1 列用于单词,1 列用于要分配的标签,每个单词和标签在一行上):

boy (\t) ID01
sleep (\t) ID02
dog (\t) ID03
hungry (\t) ID04
home (\t) ID05

原始语料库只是一个标记化的 .txt,每行一个句子,例如:

The boy and his dog met a hungry lion .
They needed to catch up on sleep after the dog and the boy came home .

理想情况下,我想要如下输出:

(1) 带标签的语料库,格式为:

The boy [ID01] and his dog [ID03] met a hungry [ID04] lion .

They needed to catch up on sleep [ID02] after the dog [ID03] and the boy [ID01] came home [ID05].

(2) 在语料库中根本找不到的带有标签的单词列表。我之前只是将这些文字打印到 .txt 文件中,而且效果很好。

我希望这是有道理的!这是我以前用来查找包含这些词的句子的方法。这段代码基于一个没有 ID 标签的更简单的单词列表,我只是在寻找任何匹配项以查看我的语料库是否至少包含一些示例。我怎样才能最好地适应它?这花了我很长时间才写,但我正在学习!

谢谢!

use strict;
use warnings;

my %words;
my %print;

open (IN2, "<LemmasFromTagset.MG.2022-10-17.txt"); #the wordlist

while (my $s = <IN2>)
{
chomp $s;
my $lcs = lc $s;
$words{$lcs} = 1;
}
close(IN2);
open (OUT, ">TaggedSentences.txt"); #the final output with tagged sentences
open (OUT2, ">NotFound.txt"); #words for which there are no sentences

foreach my $word (sort keys (%words))
{
open (IN,"<all-sentences_cleaned.tagged.desentensised.txt"); #the corpus

print $word."\n";

my $count = 0;

while(my $s = <IN>)
{
chomp $s;
my $lcs = lc $s;
if ($lcs =~ /^(.*)(\W+)($word)(\W+)(.*)$/)
{
print OUT $word."\t".$s."\n";
$count ++;
}
elsif ($lcs =~ /^($word)(\W+)(.*)$/)
{
print OUT $word."\t".$s."\n";
$count ++;
}
}

if ($count == 0)
{
print OUT2 $word."\n";
}
close(IN);
}
close(OUT);
close (OUT2);

最佳答案

我不确定我是否完全遵循您代码的逻辑,但替换很容易。

  1. 处理 key 文件,将 key 设为小写,将值设为 %words 中的标签哈希。例如。 $words{$key} = $value .我们可以使用 do 语句快速轻松地完成此操作,我们在其中提取文件并使用 map 语句处理它。
  2. 制作一个正则表达式来搜索关键词,使用交流发电机 | .
  3. 读取输入文件,找到并捕获带括号的关键字() , 保留与 \K 匹配的词.替换(添加)一个空格,标记打开,您的哈希值用 \L 变为小写转义序列和标记关闭。
  4. 打印。
use strict;
use warnings;

my %words = do {
open my $fh, "<", "words.tsv" or die $!;
map { chomp; split /\t/ } <$fh>;
};
my $find = join '|', map lc, keys %words;
while (<DATA>) {
s/($find)\K/ <$words{ "\L$1" }>/ig;
print;
}


__DATA__
The boy and his dog met a hungry lion .
They needed to catch up on sleep after the dog and the boy came home .

如果你想让这个程序更灵活,你可以直接替换<DATA><>并使用文件名作为参数进行处理,然后将输出重定向到一个文件,例如:

$ perl words.pl corpus.txt > output.txt

关于perl - 在语料库中标记单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74390729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com