作者reizarc (零式札克)
看板perl
标题Re: [问题] 请问若想取出句子中的前後几个字的话?
时间Tue Mar 20 22:41:30 2007
※ 引述《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
1F:推 Yaowei:酷 先谢过 待我思考一下^^感恩:) 03/20 22:49
2F:→ reizarc:呃 .. 不过看到条件又改了 我只针对第一篇的条件就是 >w< 03/20 22:58
3F:推 Yaowei:第一篇@@ 那应该也是可以啦 先看看好了^^ 03/21 11:14