字串列表中最常用詞的 Python 程式


當需要在字串列表中查詢最頻繁出現的單詞時,將迭代該列表並使用“max”方法獲取最高字串的計數。

範例

以下是對上述說明的演示

from collections import defaultdict
my_list = ["python is best for coders", "python is fun", "python is easy to learn"]

print("The list is :")
print(my_list)

my_temp = defaultdict(int)

for sub in my_list:
   for word in sub.split():
      my_temp[word] += 1

result = max(my_temp, key=my_temp.get)

print("The word that has the maximum frequency :")
print(result)

輸出

The list is :
['python is best for coders', 'python is fun', 'python is easy to learn']
The word that has the maximum frequency :
python

說明

  • 將必需的包匯入到環境中。

  • 定義了一個字串列表並顯示在控制檯上。

  • 建立一個整數字典並將其分配給一個變數。

  • 遍歷字串列表,並根據空格進行分割。

  • 確定每個單詞的計數。

  • 使用“max”方法確定這些值的最大值。

  • 將其分配給一個變數。

  • 將其顯示為控制檯的輸出。

更新時間:2021-09-16

4K+ 檢視次數

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.