[英]Find all occurrences of a word in a list?
我希望能夠識別單詞在句子中出現的所有位置。
例如:您好,我叫Ben,名字叫Fred。
如果輸入“名稱”,則應返回:此單詞出現在以下位置:3和8
下面是我的代碼,但是它只會返回第一個值。
text = input('Please type your sentence: ')
sentence = text.split()
word= input('Thank-you, now type your word: ')
if word in sentence:
print ('This word occurs in the places:', sentence.index(word)+1)
elif word not in sentence:
print ('Sorry, '+word+' does not appear in the sentence.')
這種理解應該做到:
[i+1 for i, w in enumerate(sentence) if w == word]
(+1,因為您希望第一個單詞為1而不是0)
完整示例:
text = input('Please type your sentence: ')
sentence = text.split()
word = input('Thank-you, now type your word: ')
if word in sentence:
print ('This word occurs in the places:')
print([i+1 for i, w in enumerate(sentence) if w == word])
elif word not in sentence:
print ('Sorry, ' + word + ' does not appear in the sentence.')
您可以通過簡單的列表理解和枚舉函數來找到索引來實現這一點。 最后加1以匹配您的期望索引。
sec = 'Hello my name is Ben and his name is Fred.'
search = input('What are you looking for? ')
print ([i + 1 for i, s in enumerate(sec.split()) if s == search])
您無法使用if做到這一點。 您必須有一個循環,如下所示:
occurrences = []
for word in sentence:
if word == target_word:
occurrences.append(sentence.index(word)+1)
您可以將數組“出現次數”中的所有出現次數都打印出來,也可以根據自己的喜好更改“打印”句子的“出現次數”。
請注意,我尚未運行此代碼,請檢查其拼寫是否正確。
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.