Python列表中找到前面和后面的单词

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'

请问如果我们中的任何一个人给出了您需要的答案,您能否选择一个有效的答案? - DevLounge
请选择一个有效的答案! - DevLounge
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)]

2
这里有一个可能性:
words = sentence.split()
[pos] = [i for (i, word) in enumerate(words) if word.endswith("GG") ]
behind = words[pos - 1]
infront = words[pos + 1]

在处理边缘情况时需要小心,例如 "…GG" 未出现、出现多次或是第一个和/或最后一个单词。目前,任何这些情况都会引发异常,这可能是正确的行为。

使用正则表达式的完全不同解决方案避免了首先将字符串拆分为数组:

match = re.search(r'\b(\w+)\s+(?:\w+GG)\s+(\w+)\b', sentence)
(behind, infront) = m.groups()

1

这是一种方法。如果“GG”单词位于句子开头或结尾,则前后元素将为

words = sentence.split()
[(infront, word, behind) for (infront, word, behind) in 
 zip([None] + words[:-1], words, words[1:] + [None])
 if word.endswith("GG")]

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

这就是你正在寻找的,希望如此。 - DevLounge

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

编辑:修正了拼写错误


属性错误:'itertools.tee'对象没有'endswith'属性。 - DevLounge

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接