繁体   English   中英

每次遇到关键字后查找下一个单词

[英]Find the next word after a keyword each time it's encountered

string = "Is your name Jack ? Wasn't your name Matthew ?"
split_string = string.split()
find_names = split_string[split_string.index("name") +1]

print(find_names)

#Output: Jack

我的目标是每次遇到关键字后都找到下一个单词,而不仅仅是第一次。 output 应该是Jack Matthew ,而不仅仅是 Jack。

index采用索引的第二个可选参数开始搜索。因此您可以遍历列表并从先前查找名称的 position 调用索引,直到找到所有名称:

ind = -1
while True:
    try:
        ind = split_string.index('name', ind + 1)
    except ValueError:
        break

    print(split_string[ind + 1])

你可以 zip 单词列表本身来制作相邻的对。 然后对于每一对,测试第一对是否是"name"

string = "Is your name Jack ? Wasn't your name Matthew ?"
split_string = string.split()

[name for test, name in zip(split_string, split_string[1:]) if test == 'name']
# ['Jack', 'Matthew']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM