使用 perl 提取文件中關鍵字之間的文本

使用 perl 提取文件中關鍵字之間的文本

如何提取關鍵字之間的文字?文字保存在 txt 或 json 檔案中。輸入是這樣的。 “適應環境和專案挑戰\n管理問題、溝通和影響技能的能力,對卓越技術和用戶體驗的熱情\n出色的組織能力,”

關鍵字是「能力」、「技能」和「經驗」。輸出應該是這些關鍵字之間的文字。在此範例中,輸出應為:

管理問題、溝通和影響力 對卓越技術和使用者體驗的熱情\n出色的組織能力

正規表示式必須準備好接受 4 或 5 個關鍵字。是否可以?

我使用了下面的程式碼,但只有當文字在程式中而不是在 txt 檔案中時它才有效。這僅適用於 2 個關鍵字。我需要幾個。

$file = 'C:\Users\Acer Nitro\Desktop\perl\sim.txt';

open(SESAME, $file);
while(<SESAME>)
{
    $text .= $_;
}

close(SESAME);
print $text;

($re=$text)=~s/((\bskill\b)|(\bability\b)|.)/${[')','']}[!$3]\Q$1\E${['(','']}[!$2]/gs;
@$ = (eval{/$re/},$@);
print join"\n",@$ unless $$[-1]=~/unmatched/;

你能幫助我嗎?

答案1

我認為你必須改變你的正規表示式。 「\ability」和「\skill」可能不是你想要的。 「\a」是「bell」的字符,「\s」是空白字符的匹配。

您想要捕獲的文字部分可以與括在括號中的正規表示式的適當部分相符。當整個 RE 找到匹配項時,可以使用 $1、$2 等訪問部分匹配的部分。

答案2

你的腳本中有很多錯誤,我已經重寫並簡化了它<

#!/usr/bin/perl 
use strict;
use warnings;
use Data::Dumper;

# file to search
my $file = 'C:\Users\Acer Nitro\Desktop\perl\sim.txt';
open my $fh, '<', $file or die "unable to open '$file' for reading: $!";
# read whole file in a single string
undef $/;
my $full = <$fh>;
# search text between keywords
my @found = $full =~ /\b(?:ability|skills|experience)\b\R?\K(.+?)(?=\b(?:ability|skills|experience)\b)/gsi;
# dump the result
print Dumper\@found;    

給定範例的輸出:

$VAR1 = [
          ' to manage issues, communications and influencing ',
          ',Passion for great technology and user ',
          'Exceptional organizational '
        ];

正規表示式解釋:

/                       # regex delimiter
    \b                  # word boundary
    (?:                 # non capture group
        ability         # literally
      |                 # OR
        skills          # literally
      |                 # OR
        experience      # literally
    )                   # end group
    \b                  # word boundary
    \R?                 # optional linebreak
    \K                  # forget all we have seen until this position
    (.+?)               # group 1, the text we want
    (?=                 # positive lookahead
        \b              # word boundary
        (?:             # non capture group
            ability     # literally
          |             # OR
            skills      # literally
          |             # OR
            experience  # literally
        )               # end group
        \b              # word boundary
    )                   # end lookahead
/gsi                    # delimiter, global; dot matches newline; case insensitive

相關內容