简体   繁体   中英

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.

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:

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. Then for each pair, test if the first of the pair is "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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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