简体   繁体   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

My goal is to find the next word after a keyword is encountered every time, not only the first time.我的目标是每次遇到关键字后都找到下一个单词,而不仅仅是第一次。 The output should be Jack Matthew instead of just Jack. output 应该是Jack Matthew ,而不仅仅是 Jack。

index takes a second optional argument of the index to begin the search in. So you could loop over the list and call index from the position of the previously find name until you find them all: index采用索引的第二个可选参数开始搜索。因此您可以遍历列表并从先前查找名称的 position 调用索引,直到找到所有名称:

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

    print(split_string[ind + 1])

You could zip the list of words with itself to make adjacent pairs.你可以 zip 单词列表本身来制作相邻的对。 Then for each pair, test if the first of the pair is "name" .然后对于每一对,测试第一对是否是"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