Python 內建強大的字串處理能力,本文透過實例詳細說明 split() 方法的各種用法,並實作英文單詞統計程式。
str.split(sep=None, maxsplit=-1) 依指定分隔符將字串切割為列表。
str_val = "a|and|hello|||ab"
alist = str_val.split('|')
print(alist)
# 輸出:['a', 'and', 'hello', '', '', 'ab']
注意: 連續分隔符會產生空字串元素。
str_val = "a hello world " # 含多個空格
alist = str_val.split() # 不傳參數:任意長度空白字元視為單一分隔符,且自動移除首尾空白
print(alist)
# 輸出:['a', 'hello', 'world']
差異重點: split(' ') 僅按單一空格切割;split() 則按任意空白字元(空格、Tab、換行)切割並忽略空元素。
以下程式讀取文本檔案,統計總單詞數、空白數與實際單詞數:
# -*- coding: utf-8 -*-
import os
# 讀取檔案
with open('c:/a.txt', 'r', encoding='utf-8') as fin:
content = fin.read()
# 按空白字元分割
words = content.split()
# 寫入每行一個單詞供檢視
with open('c:/count.txt', 'w', encoding='utf-8') as fout:
fout.write('\n'.join(words))
# 統計
total = len(words)
print(f"總單詞數(含空白分割產生的空元素):{total}")
# 若使用 split(' ') 需額外扣除空字串
words_space = content.split(' ')
actual_words = len([w for w in words_space if w])
print(f"實際單詞數:{actual_words}")
處理標點符號、多種分隔符混雜時,使用 re.split():
import re
text = "Hello, world! This is a test."
# 依非單詞字元分割,並過濾空字串
words = [w for w in re.split(r'\W+', text) if w]
print(words) # ['Hello', 'world', 'This', 'is', 'a', 'test']
split(),自動處理多重空白。