使用 Python 在字串列表中查詢字首頻率


在這篇文章中,我們將學習如何使用 Python 在字串列表中查詢字首頻率。在 Python 中解決此程式有多種方法,我們將瞭解其中的一些方法。

查詢字首頻率有助於查詢字串中單詞使用模式和分佈。

方法 1:使用簡單的 for 迴圈

示例

def find_prefix_freq(strings, prefix):
   count = 0
   for string in strings:
      if string.startswith(prefix):
         count += 1
   return count

strings = ['apple', 'aptitude', 'approve', 'aplaude','application', 'applause' 'apologize']
prefix = 'app'
print("Frequency of prefix "+ prefix + " is: "+ str(find_prefix_freq(strings, prefix)))

輸出

Frequency of prefix app is: 4

解釋

此函式接受兩個引數:字串和字首。在函式內部,我們有一個 count 變數,它將計算具有相同字首的字串的總數。使用 for 迴圈,我們將遍歷每個字串,並使用startswith() 方法檢查它是否以給定字首開頭,如果是,則 count 將增加 1。

方法 2:使用列表推導式

使用列表推導式方法,我們可以檢查查詢具有與給定字首字串相同的字首的字串。它為我們提供了一種過濾以給定字首開頭的字串的方法。

示例

def find_prefix_freq(strings, prefix):
   filtered_strings = [string for string in strings if string.startswith(prefix)]
   count = len(filtered_strings)
   return count
    
strings = ['apple', 'aptitude', 'approve', 'aplaude','application', 'applause' 'apologize']
prefix = 'app'
print("Frequency of prefix "+ prefix + " is: "+ str(find_prefix_freq(strings, prefix)))

輸出

Frequency of prefix app is: 4

解釋

此函式接受兩個引數:字串和字首。在函式內部,我們將使用列表推導式建立新的列表 filtered_strings。列表推導式迭代字串列表中的每個字串,並使用 startswith() 方法檢查字串是否以給定字首開頭。僅滿足此條件的字串才會新增到 filtered_strings 列表中。我們將使用 len() 函式獲取以給定字首開頭的字串的計數。

方法 3:使用 Counter 類

在此方法中,我們將使用 collections 模組中的 Counter 類。它為我們提供了一種簡潔的方法來計算集合中元素的出現次數。

示例

from collections import Counter

def find_prefix_freq(strings, prefix):
   pref = [string[:len(prefix)] for string in strings if string.startswith(prefix)]
   prefix_freq = Counter(pref)
   count = prefix_freq[prefix]
   return count

strings = ['apple', 'aptitude', 'approve', 'aplaude','application', 'applause' 'apologize']
prefix = 'app'
print("Frequency of prefix "+ prefix + " is: "+ str(find_prefix_freq(strings, prefix)))

輸出

Frequency of prefix app is: 4

解釋

在這裡,我們從 collections 模組匯入 Counter 類。Counter 類幫助我們找到任何列表或可迭代物件的頻率。與方法 3 相同,我們將使用列表推導式建立新的列表 pref。列表推導式將迭代列表中的每個字串,並使用 startswith() 方法檢查字串是否以給定字首開頭,並使用切片 [:len(prefix)] 提取該特定部分。透過這種方式,我們可以將滿足條件的字串新增到 pref 列表中。

之後,我們將使用 Counter 類透過傳入 pref 列表建立 prefix_freq 物件。使用 prefix_freq[pref],我們可以獲取與 pref 關聯的計數並將其分配給 count 變數。

方法 4:使用 Pandas DataFrame

當我們有更大的字串大小或字串的複雜結構時,我們可以使用 DataFrame 來計算字串列表中的字首。在這裡,我們將字串列表轉換為 DataFrame,然後使用內建函式來計算包含字首的字串。

示例

import pandas as pd

def find_prefix_freq(strings, prefix):
   df = pd.DataFrame(strings, columns=['String'])
   df['Prefix'] = df['String'].apply(lambda x: x[:len(prefix)])
   prefix_freq = df.groupby('Prefix').size().to_dict()
   count = prefix_freq.get(prefix, 0)
   return count

strings = ['apple', 'aptitude', 'approve', 'aplaude','application', 'applause' 'apologize']
prefix = 'app'
print("Frequency of prefix "+ prefix + " is: "+ str(find_prefix_freq(strings, prefix)))

輸出

Frequency of prefix app is: 4

解釋

在此程式中,我們匯入了 pandas 庫。我們的函式接受兩個引數:字串和字首。在函式內部,我們使用 pd.DataFrame() 建構函式建立了一個 DataFrame 物件 df。在建構函式中,字串列表作為資料傳遞,併為其分配了一個名為 string 的列。使用 .apply() 方法將一個新列新增到 df DataFrame 中。使用 lambda 函式,我們將對每個字串應用 [:len(prefix)] 字串切片並提取字首部分。

使用 DataFrame 上的 groupby 方法,我們將根據 prefix 列中的值對行進行分組。

方法 5:使用正則表示式

正則表示式被認為是用於複雜字串結構的模式匹配的非常強大的工具。在這裡,我們使用“re”模組搜尋與給定字首匹配的字串並計算匹配的總數。

示例

import re

def find_prefix_freq(strings, prefix):
   pattern = f'^{prefix}'
   count = sum(1 for string in strings if re.match(pattern, string))
   return count

strings = ['apple', 'aptitude', 'approve', 'aplaude','application', 'applause' 'apologize']
prefix = 'app'
print("Frequency of prefix "+ prefix + " is: "+ str(find_prefix_freq(strings, prefix)))

輸出

Frequency of prefix app is: 4

解釋

在上面的程式中,我們匯入了正則表示式,這對於字首匹配是必需的。在函式內部,我們將首先使用 ^ 符號構造正則表示式,它表示字串的開頭,後跟字首。構造正則表示式後,我們將使用列表推導式技術迭代列表中的每個字串,並首先對每個字串使用 re.match() 函式檢查它是否與我們使用正則表示式構造的模式匹配。如果模式匹配,我們將增加我們的計數。

因此,這些是一些可用於查詢字串列表中字首頻率的方法。每種方法都有其自身的優勢,例如效能和簡單性。使用這些方法,您可以從字串中提取有價值的資訊。您可以根據您的偏好和預期效能選擇任何方法並應用它以獲得有關字首頻率的洞察力。

更新於:2023-10-13

197 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.