簡體   English   中英

Python 僅查找字符串中單詞的第一個實例

[英]Python find ONLY the first instance of a word in a string

Python 新手在這里。 我想提取在列表中找到第一個單詞的句子。 目前,它正在提取所有包含單詞“dog”和“cat”的字符串。 我試過(i.split('.')[0])但這也不起作用。 有人可以幫忙嗎?

text= 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '

lst=[]
words=['dog', 'cat', 'chocolate']
for i in text.split('.'):
    for j in words:
        if j in i:
            print(i.split('.')[0])
            lst.append (i.split('.')[0]) 
else:
    lst.append('na')
    print('na')

輸出:

the dog was there

the cat is there too

the dog want want want was there

na

期望的輸出:

the dog was there

the cat is there too

n/a (because choclate is not found)

謝謝你!

無需對代碼進行大量更改,即可通過在“單詞”列表中使用“刪除”來實現輸出。

text= 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '

lst=[]
words=['dog', 'cat', 'chocolate']
for i in text.split('.'):
    for j in words:
        if j in i:
            print(i.split('.')[0])
            words.remove(j) # this will remove the matched element from your search list
            lst.append (i.split('.')[0]) 
else:
    lst.append('na')
    print('na')

如果您反轉循環,則可以使用break轉到下一個單詞:

text= 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '

lst=[]
words=['dog', 'cat', 'chocolate']
for j in words: # each word
    for i in text.split('.'):  # each sentence
        if j in i:
            print(i.split('.')[0])
            lst.append (i.split('.')[0]) 
            break  # next word
else:
    lst.append('na')
    print('na')

輸出:

the dog was there
 the cat is there too
na

一個可能的解決方案可能是跟蹤您找到了哪些單詞。 如果您可以修改words列表,則可以這樣做:

text= 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '

lst=[]
words=['dog', 'cat', 'chocolate']
for sentence in text.split('.'):
    sentence = sentence.strip()  # Remove whitespace around sentence
    for word in words:
        if word in sentence:
            print(sentence)
            lst.append(sentence) 
            # Remove the found word from words
            words.remove(word)
else:
    lst.append('na')
    print('na')

我還更改了一些變量名稱,以使代碼更易於閱讀。 這段代碼輸出如下

the dog was there
the cat is there too
na

縮小你的代碼(只有一個 for 循環),你可以在單詞列表上使用pop()從那里刪除一個項目:

text = 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '
sentences = text.split('.')
words=['dog', 'cat', 'chocolate']

for sentence in sentences:
    # Takes the first word as long as there are items in the list!
    word = words.pop(0) if words else None
    if word and word in sentence:
        print(sentence.strip())  # Removes whitespaces arround the sentence 
else:
    print('na')

輸出:

the dog was there
the cat is there too
na

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM