Re: [問題] 請問若想取出句子中的前後幾個字的話?

看板Perl作者 (零式札克)時間18年前 (2007/03/20 22:41), 編輯推噓2(201)
留言3則, 2人參與, 最新討論串4/4 (看更多)
※ 引述《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
呃 .. 不過看到條件又改了 我只針對第一篇的條件就是 >w<
03/20 22:58, 2F

03/21 11:14, , 3F
第一篇@@ 那應該也是可以啦 先看看好了^^
03/21 11:14, 3F
文章代碼(AID): #15__AR8Z (Perl)
文章代碼(AID): #15__AR8Z (Perl)