簡體   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