Re: [問題] 請問若想取出句子中的前後幾個字的話?
※ 引述《Yaowei (成就你的大事)》之銘言:
: 若我想找出有符合下列樣版中的字
: interaction,interactions,interacts
: 並由它們其中之一個取出如下的內容:
: 往前或後後推直到找到前後各有一個<PTN> 的兩個字,若前/後無<PTN>則往另一方向取出
: 兩個<PTN>為止,若往前時是句首則停止,若往後的第二個字是.則也是停止。
: 請問該如何作呢?
: ----------------------------------------------------------------------------
: 比對到:interaction
: <PTN> mRNA coimmunoprecipitated with <PTN> in resting synaptoneurosomes, but
: the interaction was lost shortly after <PTN> treatment.
: ---------------------------------------------------------------------------
: 比對到:interactions
: Our data suggest that physical interactions between <PTN> and <PTN> mRNA
: underlie translational repression,
: ----------------------------------------------------------------------------
: 比對到:interacts
: 來源:
: <PTN> interacts with <PTN> RNA as well as a number of <PTN>,
: ----------------------------------------------------------------------------
用硬幹的解 >w< ... 至少可以符合上面的條件
因為我想了半天 原本列的那些條件 我覺得用 regexp 好像不會比較方便 Orz
&func( $string ); # 用上面給的例子輸入
sub func
{
$str = shift;
@terms = split ' ', $str;
$matchIdx = -1;
@tagBefore = ();
@tagAfter = ();
$i = 0;
foreach( @terms ) # 拆開掃一遍
{
if( '<PTN>' eq $_ )
{
if( -1 == $matchIdx )
{
push( @tagBefore, $i ); # 在前面的 <PTN> 位置
}
else
{
push( @tagAfter, $i ); # 後面的
}
}
elsif( 'interaction' eq $_ or # match 的位置
'interactions' eq $_ or
'interacts' eq $_ )
{
$matchIdx = $i;
}
$i ++;
}
if( !@tagBefore ) # 前面沒有 <PTN>, 找後面兩個並延伸
{
$tagAfter[ 1 ] += 2;
$tagAfter[ 1 ] = $#terms if( $tagAfter[ 1 ] > $#terms );
print join( ' ', @terms[ $matchIdx .. $tagAfter[ 1 ] ] ), $/;
}
elsif( !@tagAfter ) # 後面沒有 <PTN>, 找前面兩個並延伸
{
$tagBefore[ -2 ] -= 2;
$tagBefore[ -2 ] = 0 if( $tagBefore[ -2 ] < 0 );
print join( ' ', @terms[ $tagBefore[ -2 ] .. $matchIdx ] ), $/;
}
else # 前後都有, 各找一個
{
$tagAfter[ 0 ] += 2;
$tagAfter[ 0 ] = $#terms if( $tagAfter[ 0 ] > $#terms );
$tagBefore[ -1 ] -= 2;
$tagBefore[ -1 ] = 0 if( $tagBefore[ -1 ] < 0 );
print join( ' ', @terms[ $tagBefore[ -1 ] .. $tagAfter[ 0 ] ] ), $/;
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.216.192.219
推
03/20 22:49, , 1F
03/20 22:49, 1F
→
03/20 22:58, , 2F
03/20 22:58, 2F
推
03/21 11:14, , 3F
03/21 11:14, 3F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 4 之 4 篇):
Perl 近期熱門文章
PTT數位生活區 即時熱門文章