Python程式查詢字串列表中公共元素的頻率


在這篇 Python 文章中,給定的任務是獲取字串列表中公共元素的頻率。有時,使用 Python 分析的列表存在於 Excel 檔案中。要從 Excel 獲取此列表,使用一個名為 openpyxl 的模組。在這篇 Python 文章中,透過三個不同的示例,給出了獲取字串列表中重複項頻率的方法。在示例 1 中,找到了字串列表中公共字元的頻率。在接下來的兩個示例中,給出了方法,其中給出了字串列表中公共單詞的頻率。在這些示例中,字串列表是從 Excel 檔案的列中獲取的。

預處理步驟

步驟 1 − 使用 Google 帳戶登入。轉到 Google Colab。開啟一個新的 Colab 筆記本,並在其中編寫 Python 程式碼。

步驟 2 − 首先將 Excel 檔案“oldrecord5.xlsx”上傳到 Google Colab。

步驟 3 − 匯入“openpyxl”。

步驟 4 − 使用 openpyxl.load_workbook 函式載入 Excel 檔案。

步驟 5 − 在名為 myxlsxsheet 的變數中開啟活動工作表

步驟 6 − 使用 Pandas 將此字串列提取到資料框中。

步驟 7 − 將資料框轉換為列表。將此列表稱為“title_list”

這些示例中使用的 Excel 檔案內容

                                      

圖:顯示示例中使用的 Excel 檔案 oldrecord5.xls

將 Excel 檔案上傳到 colab

                                    

圖:將 oldrecord5.xls 上傳到 Google Colab

示例 1:使用 reduce 函式獲取字串列表中找到的字元的頻率

在這種方法中,使用了 reduce 函式。

步驟 1 − 使用來自上述預處理步驟的列表“title_list”。

步驟 2 − 使用 reduce、lambda 和 Counter 查詢這些字串中所有公共字元的字元頻率。

步驟 3 − 以字典的形式顯示結果。

在 Google Colab 工作表的程式碼單元格中編寫以下程式碼

import openpyxl
from openpyxl import load_workbook
import pandas as pd
from functools import reduce
from collections import Counter
# load excel file with its path
myxlsx = openpyxl.load_workbook("oldrecord5.xlsx")
myxlsxsheet = myxlsx.active

# Convert to DataFrame
df = pd.DataFrame(myxlsxsheet.values)

#Select those rows that contain "Discussion" String
df1=df[df.iloc[:,3].str.contains('Discussion')]

#Select only the titles' column 
df2 = df1.iloc[:,3]

title_list=df2.values.tolist()
print(title_list)

itemFreq = reduce(lambda m, n: m & n, (Counter(elem) for elem in title_list[1:]),Counter(title_list[0]))

print("Common Characters and their occurrence : " , str(dict(itemFreq)))

檢視結果

按下程式碼單元格上的播放按鈕以檢視結果。

['Types of Environment - Class Discussion', 'Management Structure and Nature  - Class Discussion', 'Macro- Demography, Natural, Legal & Political  - Class Discussion']
Common Characters and their occurrence :  {'e': 2, 's': 5, ' ': 5, 'o': 1, 'n': 1, 'i': 2, 'r': 1, 'm': 1, 't': 1, '-': 1, 'C': 1, 'l': 1, 'a': 1, 'D': 1, 'c': 1, 'u': 1}

圖 1:顯示使用 Google Colab 的結果。

示例 2:透過組合和排序列表獲取字串列表中找到的單詞的頻率

要遵循此方法,我們使用了以下步驟

步驟 1 − 使用來自上述預處理步驟的列表“title_list”。

步驟 2 − 對單個列表項使用 split 將其分成單詞,然後將這些單詞組合成一個組合列表。

步驟 3 − 對此組合列表進行排序,並使用 Counter 查詢頻率。以字典的形式顯示結果。

在 Google Colab 工作表的程式碼單元格中編寫以下程式碼。

from collections import Counter
import openpyxl
from openpyxl import load_workbook
import pandas as pd

# load excel file with its path
myxlsx = openpyxl.load_workbook("oldrecord5.xlsx")
myxlsxsheet = myxlsx.active

# Convert to DataFrame
df = pd.DataFrame(myxlsxsheet.values)

#Select those rows that contain "Discussion" String
df1=df[df.iloc[:,3].str.contains('Discussion')]

#Select only titles' column 
df2 = df1.iloc[:,3]

title_list=df2.values.tolist()
print(title_list)
lst1= title_list[0].split()
lst2= title_list[1].split()
lst3= title_list[2].split()
combinedlist = [*lst1, *lst2, *lst3]

# Print output
print("Concatenated List: ",combinedlist)

for elem in sorted(combinedlist):
   print(elem)

frequencyofelements=Counter(combinedlist)
print("frequency of elements: ",frequencyofelements)

示例 2 的輸出

要檢視 colab 中的結果,請按下程式碼單元格上的播放按鈕。

['Types of Environment - Class Discussion', 'Management Structure and Nature  - Class Discussion', 'Macro- Demography, Natural, Legal & Political  - Class Discussion']
Concatenated List:  ['Types', 'of', 'Environment', '-', 'Class', 'Discussion', 'Management', 'Structure', 'and', 'Nature', '-', 'Class', 'Discussion', 'Macro-', 'Demography,', 'Natural,', 'Legal', '&', 'Political', '-', 'Class', 'Discussion']
&
-
-
-
Class
Class
Class
Demography,
Discussion
Discussion
Discussion
Environment
Legal
Macro-
Management
Natural,
Nature
Political
Structure
Types
and
of
frequency of elements:  Counter({'-': 3, 'Class': 3, 'Discussion': 3, 'Types': 1, 'of': 1, 'Environment': 1, 'Management': 1, 'Structure': 1, 'and': 1, 'Nature': 1, 'Macro-': 1, 'Demography,': 1, 'Natural,': 1, 'Legal': 1, '&': 1, 'Political': 1})

圖 2:顯示使用 Google Colab 的結果。

示例 3:使用 Pandas 及其函式獲取字串列表中找到的單詞的頻率

要遵循此方法,我們使用了以下步驟

步驟 1 − 使用來自上述預處理步驟的列表“title_list”。

步驟 2 − 對單個列表項使用 split 將其分成單詞,然後將這些單詞組合成一個組合列表。

步驟 3 − 使用 Pandas Series,然後使用 value_counts() 函式計算所用單詞的頻率。顯示輸出。

在 Google Colab 工作表的程式碼單元格中編寫以下程式碼。

import openpyxl
from openpyxl import load_workbook
import pandas as pd

# load excel file with its path
myxlsx = openpyxl.load_workbook("oldrecord5.xlsx")
myxlsxsheet = myxlsx.active

# Convert to DataFrame
df = pd.DataFrame(myxlsxsheet.values)

#Select those rows that contain "Discussion" String
df1=df[df.iloc[:,3].str.contains('Discussion')]

#Select only titles' column 
df2 = df1.iloc[:,3]

title_list=df2.values.tolist()
print(title_list)
lst1= title_list[0].split()
lst2= title_list[1].split()
lst3= title_list[2].split()

#combinedlist = [*lst1, *lst2, *lst3, *lst4, *lst5]
combinedlist = [*lst1, *lst2, *lst3]
# Print output
print("Concatenated List: ",combinedlist)

frequencyofelements = pd.Series(combinedlist).value_counts()
print("frequency of elements: ") 
print(frequencyofelements)   

檢視結果

按下程式碼單元格上的播放按鈕以檢視結果

['Types of Environment - Class Discussion', 'Management Structure and Nature  - Class Discussion', 'Macro- Demography, Natural, Legal & Political  - Class Discussion']
Concatenated List:  ['Types', 'of', 'Environment', '-', 'Class', 'Discussion', 'Management', 'Structure', 'and', 'Nature', '-', 'Class', 'Discussion', 'Macro-', 'Demography,', 'Natural,', 'Legal', '&', 'Political', '-', 'Class', 'Discussion']
frequency of elements: 
-              3
Class          3
Discussion     3
Types          1
of             1
Environment    1
Management     1
Structure      1
and            1
Nature         1
Macro-         1
Demography,    1
Natural,       1
Legal          1
&              1
Political      1
dtype: int64

在這篇 Python 文章中,透過三個不同的示例,給出了顯示如何查詢字串列表中找到的元素頻率的方法。在第一個示例中,給出了透過將元素視為字串中出現的簡單字元來執行此操作的方法。在示例二和三中,首先將字串分隔成單個有意義的單詞,然後將它們用作元素以獲取頻率。

更新於: 2023年7月10日

139 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告