3

これは次の質問に関連しています - Python での Unicode 文字の検索

私はこのような文字列を持っています -

sentence = 'AASFG BBBSDC FEKGG SDFGF'

私はそれを分割し、以下のような単語のリストを取得します-

sentence = ['AASFG', 'BBBSDC', 'FEKGG', 'SDFGF']

次のコードを使用して単語の一部を検索し、単語全体を取得します-

[word for word in sentence.split() if word.endswith("GG")]

戻る['FEKGG']

今、私はその言葉の前後にあるものを見つける必要があります.

たとえば、「GG」を検索すると、 が返されます['FEKGG']。また、取得できるはずです

behind = 'BBBSDC'
infront = 'SDFGF'
4

5 に答える 5

3

このジェネレーターの使用:

次の文字列がある場合(元から編集):

sentence = 'AASFG BBBSDC FEKGG SDFGF KETGG'

def neighborhood(iterable):
    iterator = iter(iterable)
    prev = None
    item = iterator.next()  # throws StopIteration if empty.
    for next in iterator:
        yield (prev,item,next)
        prev = item
        item = next
    yield (prev,item,None)

matches = [word for word in sentence.split() if word.endswith("GG")]
results = []

for prev, item, next in neighborhood(sentence.split()):
    for match in matches:
        if match == item:
            results.append((prev, item, next))

これは以下を返します:

[('BBBSDC', 'FEKGG', 'SDFGF'), ('SDFGF', 'KETGG', None)]
于 2013-08-11T11:15:29.953 に答える
1

別の itertools ベースのオプションは、大規模なデータセットでよりメモリに優しい場合があります

from itertools import tee, izip
def sentence_targets(sentence, endstring):
   before, target, after = tee(sentence.split(), 3)
   # offset the iterators....
   target.next()
   after.next()
   after.next()
   for trigram in izip(before, target, after):
       if trigram[1].endswith(endstring): yield trigram

編集:タイプミスを修正

于 2013-08-11T21:53:48.250 に答える
1

これは一つの方法です。infront 要素と behind 要素はNone、「GG」という単語が文頭または文末にある場合になります。

words = sentence.split()
[(infront, word, behind) for (infront, word, behind) in 
 zip([None] + words[:-1], words, words[1:] + [None])
 if word.endswith("GG")]
于 2013-08-11T20:37:38.227 に答える
1
sentence = 'AASFG BBBSDC FEKGG SDFGF AAABGG FOOO EEEGG'

def make_trigrams(l):
    l = [None] + l + [None]

    for i in range(len(l)-2):
        yield (l[i], l[i+1], l[i+2])


for result in [t for t in make_trigrams(sentence.split()) if t[1].endswith('GG')]:
    behind,match,infront = result

    print 'Behind:', behind
    print 'Match:', match
    print 'Infront:', infront, '\n'

出力:

Behind: BBBSDC
Match: FEKGG
Infront: SDFGF

Behind: SDFGF
Match: AAABGG
Infront: FOOO

Behind: FOOO
Match: EEEGG
Infront: None
于 2013-08-11T21:32:13.617 に答える