在 Python 中計算字串中的單詞

  1. 使用 split()len() 方法計算 Python 字串中的字數
  2. 使用 RegEx 模組計算 Python 字串中的單詞
  3. 使用 sum()strip()split() 方法計算 Python 字串中的字數
  4. 使用 count() 方法計算 Python 字串 Python 中的單詞數
在 Python 中計算字串中的單詞

本教程將介紹如何在字串 Python 中統計單詞。

使用 split()len() 方法計算 Python 字串中的字數

split() 是 Python 中的一個內建方法,它通過使用特定的分隔符來分隔字串中的單詞並返回一個字串陣列。此方法最多接受兩個引數作為引數:

  • separator(可選) - 它充當分隔符(例如逗號、分號、引號或斜線)。指定要在字串中分隔的邊界。如果未指定 separator,預設 separator 是任何空格(空格、換行符、製表符等)。
  • maxsplit(可選) - 它定義了最大分割數。如果未定義 maxsplit 的預設值是 -1,這意味著它沒有限制並將字串拆分為多個塊。

split() 的語法:

str.split(separator, maxsplit)

len() 也是一個 Python 內建方法,它返回陣列中字串的數量或計算物件中專案的長度。此方法只接受一個引數:字串、位元組、列表、物件、集合或集合。如果引數丟失或無效,它將引發 TypeError 異常。

len() 的語法:

len(s)

讓我們看看 split()len() 方法如何計算字串中的單詞數。

示例 1:無引數

# initialize string
text = "The quick brown fox jumps over the lazy dog"

# default separator: space
result = len(text.split())

print("There are " + str(result) + " words.")

輸出:

There are 9 words.

示例 2:使用 separator 引數

# initialize string
bucket_list = "Japan, Singapore, Maldives, Europe, Italy, Korea"

# comma delimiter
result = len(bucket_list.split(","))

# Prints an array of strings
print(bucket_list.split(","))

print("There are " + str(result) + " words.")

輸出:

['Japan', ' Singapore', ' Maldives', ' Europe', ' Italy', ' Korea']
There are 6 words.

split() 方法將返回一個新的字串列表,len() 計算列表中的字串。

示例 3:使用 separatormaxsplit 引數

# initialize string
bucket_list = "Japan, Singapore, Maldives, Europe, Italy, Korea"

# comma delimiter
result = len(bucket_list.split(",", 3))

# Prints an array of strings
print(bucket_list.split(",", 3))

print("There are " + str(result) + " words.")

輸出:

['Japan', ' Singapore', ' Maldives', ' Europe, Italy, Korea']
There are 4 words.

maxsplit 只拆分 bucket_list 中的前三個逗號。如果你設定了 maxsplit,列表就會有一個 maxsplit+1 項。

輸出:

['Japan', ' Singapore', ' Maldives, Europe, Italy, Korea']
There are 3 words.

split() 方法將大字串分解成更小的字串。因此,字串陣列中單詞的計數將不完全基於單詞,而是基於拆分分隔符的定義方式。

使用 RegEx 模組計算 Python 字串中的單詞

正規表示式,簡稱 regexregexp,是一個非常強大的搜尋和操作文字字串的工具;這可用於資料預處理、驗證目的、在文字字串中查詢模式等。正規表示式還可以幫助計算文字字串中包含不需要的標點符號或特殊字元的情況下的單詞數。Regex 是一個 Python 內建包,所以我們只需要匯入包 re 即可開始使用它。

# import regex module
import re

# initialize string
text = "Python !! is the be1st $$             programming language @"

# using regex findall()
result = len(re.findall(r"\w+", text))

print("There are " + str(result) + " words.")

輸出:

There are 6 words.

使用 sum()strip()split() 方法計算 Python 字串中的字數

這種方法在不使用正規表示式的情況下計算單詞。sum()strip()split() 都是 Python 中的內建方法。我們將簡要討論每種方法及其功能。

sum() 方法從左到右將專案相加並返回總和。該方法有兩個引數:

  • iterable(必需)- 一個字串、列表、元組等,要加起來。這些應該是數字。
  • start(可選)- 新增到方法的總和或返回值的數字。

sum() 的語法:

sum(iterable, start)

下一個是 strip() 方法,如果沒有引數,它返回去除前導和尾隨空格的字串的副本;否則,這將刪除引數中定義的字串。

  • chars(可選)- 指定要從文字左右部分刪除的字串。

string.strip() 的語法:

string.strip(chars)

最後,split() 方法在此方法之前已經討論過。

現在,讓我們一起使用這些方法來計算字串中的單詞數。首先,在使用其功能之前,我們需要匯入 string,這是一個 Python 內建模組。

import string

# initialize string
text = "Python !! is the be1st $$             programming language @"

# using the sum(), strip(), split() methods
result = sum([i.strip(string.punctuation).isalpha() for i in text.split()])

print("There are " + str(result) + " words.")

輸出:

There are 5 words.

使用 count() 方法計算 Python 字串 Python 中的單詞數

count() 方法是 Python 的內建方法。它接受三個引數並根據給定的子字串返回出現次數。

  • substring(必需)- 要在字串中搜尋的關鍵字
  • start(選項)- 搜尋開始位置的索引
  • end(選項)- 搜尋結束位置的索引
注意
在 Python 中索引從 0 開始。

count() 的語法:

string.count(substring, start, end)

此方法與前面的方法不同,因為它不返回在字串中找到的單詞總數,而是返回給定子字串的出現次數。讓我們從下面的例子中看看這個方法是如何工作的:

# initialize string
text = "Python: How to count words in string Python"
substring = "Python"

total_occurrences = text.count(substring)

print("There are " + str(total_occurrences) + " occurrences.")

輸出:

There are 2 occurrences.

在這種方法中,子串是整個單詞、短語、字母還是字元或數字的任意組合都沒有關係。

總之,你可以根據你的用例選擇這些方法中的任何一種。對於空格分隔的單詞,我們可以使用簡單的方法:函式 split()len()。要過濾文字字串以計算沒有特殊字元的單詞,請使用 regex 模組。建立一個計算不包含某些字元的單詞的模式。不使用 regex,使用 sum() + strip() + split() 方法組合的替代方法。最後,count() 方法也可用於計算字串中找到的特定單詞。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

相關文章 - Python String