我想創建一個函式,它將字串串列作為輸入,并且對于給定的單詞,回傳一個元組,其中包含給定單詞提及次數最多的字串以及字串中提及次數。如果多個字串都具有相同的單詞最大提及次數,則回傳這些字串中第一個出現的單詞。該詞不區分大小寫。
例如,考慮以下串列:
Tomatoes = ['tonight tomatoes grow towards the torchlit tower',
'the birds fly to the sky',
'to take the fish to the sea and to tell the tale',
'to fly to the skies and to taste the clouds']
請注意,第 3 行和第 4 行中提到的單詞最多'to'。當我們使用 searchword 將西紅柿放入函式時‘to’,它應該如下所示:
most_word_mentions(Tomatoes, ‘to’)
并且它應該回傳字串中的第三行和“to”的提及量作為一個元組,它應該看起來像(3, 3)。盡管第 3 行與第 4 行共享相同數量的單詞提及,但它被回傳,因為它出現在串列的第一個位置。
我創建了一個可以部分實作我想要的功能,但是在特定條件下它會失敗。
def most_word_mentions(message, word):
wordcount = []
for i in range(len(message)):
message[i] = message[i].lower() #word is not case sensitive
wordcount.append(((message[i]).count(word)))
return (wordcount.index(max(wordcount)) 1), max(wordcount)
如果我們輸入most_word_mentions(Tomatoes, ‘to’),則該函式無法輸出正確的行和單詞提及。相反,它回傳(1, 6). 這是因為第 1 行雖然不包含明確的單詞“to”,但包含許多其他帶有“to”的單詞。我想寫一個函式來解決這個問題,并且可以應用于類似的場景。這可以僅使用 for 回圈和沒有串列理解或匯入的 if 陳述句來完成嗎?
uj5u.com熱心網友回復:
此解決方案僅使用您需要的 for 回圈和 if 陳述句。
def most_word_mentions(list_of_strings, word):
word = word.lower()
highest_count = 0
earliest_index = 0
for i in range(len(list_of_strings)):
curr_count = 0
if word in list_of_strings[i].lower():
curr_count = list_of_strings[i].lower().count(word)
if curr_count > highest_count:
if i > earliest_index:
earliest_index = i
highest_count = curr_count
return (earliest_index 1, highest_count)
print(most_word_mentions(Tomatoes, 'to'))
輸出:
(3,3)
uj5u.com熱心網友回復:
這是我開始的一個,它遵循一個稍微不同的想法:
def mostCommon(word,sentences):
sentencecount={} # keep track of sentences and occurance in sentence
for item in sentences: #iterate through sentences
lowcasesentence=item.lower().split() #make sentence lowercase, and split so that there is a list with each word of the sentence
sentencecount[item]=lowcasesentence.count(word) #call the method "count", which counts all occurances in a list. Append that to sentencecount
return(sentencecount) # return sentences as a dictionary with count as their value.
您應該將句子拆分為單詞并對其進行計數,而不是遍歷每個字母組合。請注意,我的函式會回傳所有句子,而不僅僅是字數最多的句子。
uj5u.com熱心網友回復:
你可以試試這個。
def most_word_mentions(message, word):
word = word.lower()
line = 0
most = 0
for i in range(len(message)):
count = 0
for w in message[i].lower().split():
if word == w:
count = 1
if count > most:
line = i 1
most = count
return (line, most)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/460678.html
上一篇:IF陳述句是否匹配資料范圍
