解析一个字符串,找到下一个特定单词的下一个单词并返回下一个单词

2024-10-02 14:28:10 发布

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

有一句话:【‘这是我的钢笔’,‘瓶子是半透明的’】

需要在每个元素中返回下一个单词“is”的脚本

首选输出:['my','translucent']


Tags: 脚本元素瓶子ismy单词半透明钢笔
3条回答

介于itertools overkill和c风格python之间:

在单词(锚定词、短语)后定义单词:
单词=短语。拆分(“”)
enum=枚举(单词)
对于idx,枚举中的项:
如果锚定==项目:
中断
返回下一个(枚举)

结果=单词后面的单词('is',['this is my pen','bottle is translucent'][0])
打印(f“result{result}”)

代码(非常简单的方法):

l = ['this is my pen','bottle is translucent']

res = []
for i in range(len(l)):
    words = l[i].split()
    length = len(words)
    for c in range(length):
        if words[c] == "is":
            res.append(words[c+1])

输出:

['my', 'translucent']

一种itertools变体。。。有点过分了:

from itertools import dropwhile, islice

lst = ["this is my pen", "bottle is translucent"]

new = [
    next(islice(dropwhile(lambda word: word != "is", phrase.split()), 1, None))
    for phrase in lst
]

print(new)  # ['my', 'translucent']

更简单:

new = []
for phrase in lst:
    splt = phrase.split()
    new.append(splt[splt.index("is") + 1])

相关问题 更多 >