在Python lis的前后找到单词

2024-10-03 23:19:13 发布

您现在位置:Python中文网/ 问答频道 /正文

这和下面的问题有关-Searching for Unicode characters in Python

我有这样的绳子-

sentence = 'AASFG BBBSDC FEKGG SDFGF'

我把它分开,得到了下面这样的单词列表-

^{pr2}$

我用下面的代码搜索一个单词的一部分,然后得到整个单词-

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

它返回['FEKGG']

现在我要找出这个词的前后。在

例如,当我搜索“GG”时,它返回['FEKGG']。它也应该能够

behind = 'BBBSDC'
infront = 'SDFGF'

Tags: in列表forsearchingunicode单词sentenceword
3条回答

这是一种方法。如果“GG”这个词在句子的开头或结尾,前面和后面的元素将是None。在

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

Using this generator:

如果您有以下字符串(从原始值编辑):

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))

这将返回:

^{pr2}$

有一种可能:

words = sentence.split()
[pos] = [i for (i, word) in enumerate(words) if word.endswith("GG") ]
behind = words[pos - 1]
infront = words[pos + 1]

您可能需要注意边缘情况,例如"…GG"没有出现、出现不止一次,或者是第一个和/或最后一个单词。按照目前的情况,任何一种情况都会引发一种例外,这很可能是正确的行为。在

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

^{pr2}$

相关问题 更多 >