首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 字串分割與英文單詞統計實戰教學

     編輯:更多程式設計知識

Python 內建強大的字串處理能力,本文透過實例詳細說明 split() 方法的各種用法,並實作英文單詞統計程式。

字串分割基礎:split() 方法

str.split(sep=None, maxsplit=-1) 依指定分隔符將字串切割為列表。

範例 1:指定分隔符號


str_val = "a|and|hello|||ab"
alist = str_val.split('|')
print(alist)
# 輸出:['a', 'and', 'hello', '', '', 'ab']

注意: 連續分隔符會產生空字串元素。

範例 2:預設分割(空白字元)


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(),自動處理多重空白。
  • 統計單詞時建議搭配正則表達式移除標點符號。
  • 大檔案處理可使用生成器逐行讀取,避免記憶體溢位。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved