Python - 字串中可能存在的子串計數


本文我們將學習各種方法,利用這些方法可以計算給定字串中子串的個數。在使用 Python 時,您可能遇到過需要檢查給定單詞在一個句子或任何字串中出現了多少次的情況,因此,為了獲得較長主字串中子串的計數,我們將看到一些程式。

方法 1:使用 count 方法

這是一種簡單易用的 Python 內建方法,允許我們計算主字串中的子串個數。其時間複雜度為 O(n)。

示例

def count_substr_possible(str, substr):
   count = str.count(substr)
   return count
str="soneduonempaone"
substr="one"
print("Substring count is:",count_substr_possible(str, substr))

輸出

Substring count is: 3

解釋

在此函式中,我們將要計數的字串和子串作為引數傳遞,並將子串賦值給字串的 count 函式。此 count() 方法將返回子串出現的總次數。在字串“soneduonempaone”中,子串“one”出現了 3 次,因此結果將為 3,這是字串中子串的總數。

方法 2:使用正則表示式

此方法允許我們處理字串,例如子串匹配和計數。它還具有查詢高階模式匹配的功能。

示例

import re

def count_substr_possible(str, substring):
   count = len(re.findall(substring, str))
   return count
str="soneduonempaone"
substr="one"
print("Substring count is:",count_substr_possible(str, substr))

輸出

Substring count is: 3

解釋

在此程式中,我們匯入正則表示式庫,並使用 're' 中的 findall 函式查詢字串中子串的所有出現。findall() 函式返回匹配子串的列表,並使用 len() 函式查詢列表的長度,這將作為主字串中子串的總出現次數。

方法 3:使用迴圈和 find() 函式

在此方法中,我們迭代給定的字串,並使用 string.find() 函式查詢子串的出現次數。

示例

def count_substr_possible(str, substr):
   count = 0
   index = 0

   while index != -1:
      index = str.find(substr, index)
      if index != -1:
         count += 1
         index += 1

      return count

str="soneduonempaone"
substr="one"
print("Substring count is:",count_substr_possible(str, substr))

輸出

Substring count is: 1

解釋

在上面的程式中,我們建立了兩個變數 count 和 index,其中 count 初始化為 0,因為最初子串計數為 0。我們將使用 find() 函式檢查子串的出現,從初始索引開始,直到它返回 -1。如果出現子串(例如索引不為 -1),則我們將 count 加 1。

方法 4:使用比較和切片

使用此方法,我們執行切片和比較操作來計算字串中子串出現的總次數。

示例

def count_substr_possible(str, substr):
   count = 0
   sub_len = len(substr)

   for i in range(len(str) - sub_len + 1):
      if str[i:i + sub_len] == substr:
         count += 1

      return count

str="soneduonempaone"
substr="one"
print("Substring count is:",count_substr_possible(str, substr))

輸出

Substring count is: 0

解釋

與方法 4 示例相同,我們將建立一個 count 變數,其初始值為 0,它將儲存子串出現的總次數。我們將遍歷字串,從 0 到字串的長度,並將使用從當前位置 i 開始的子串的切片操作。

示例

from itertools import combinations

def count_substr_possible(str, substr):
   count = 0
   sub_len = len(substr)

   for length in range(sub_len, len(str) + 1):
      for i in range(len(str) - length + 1):
         sub = ''.join(str[i:i+length])
         if sub == substr:
            count += 1

   return count

str = "soneduonempaone"
substr = "one"


print("Substring count is:",count_substr_possible(str, substr))

輸出

Substring count is: 3

解釋

在此程式中,我們從 itertools 匯入了 combinations。我們的名為 count_substr_possible 的函式將字串和子串作為兩個引數。使用兩個巢狀迴圈,我們將生成字串中字元的組合,外迴圈將從子串的長度遍歷到較長字串的長度以生成不同長度的子串。然後,我們將使用等號比較子串,如果它們相等,則我們將 count 變數加 1。

因此,我們看到了一些可以找到較長字串中子串總數的方法。我們看到了四種不同的方法來使用 Python 語言解決這個問題。在所有四種方法中,string.count() 方法具有非常簡單有效的解決方案方法,而正則表示式匹配提供了一種非常有效的方法來查詢複雜的模式匹配場景。切片和比較也為我們提供了一種非常簡單的方法來計算子串出現的次數。因此,您可以根據需要和易用性選擇任何方法,但瞭解不同的方法可以幫助您更好地學習。

更新於:2023年10月13日

97 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.