Python 常用字串操作
theme: hydrogen
攜手創作,共同成長!這是我參與「掘金日新計劃 · 8 月更文挑戰」的第4天,點選檢視活動詳情
前言
在處理文字資料時,我們通常需要對其進行多種不同的操作,例如在文字後追加新的字串、將文字拆分為多個字串,或修改字母的大小寫等;當然,除此之外,我們也會需要使用更高階的文字解析或其他方法;但是,將文字劃分為句子或者單詞、刪除或替換某些特定單詞等這類的操作是最常見的。
字串操作
接下來,我們將通過一些例項來介紹常用的基本字串操作。首先,定義一段文字,對其進行拆分,並進行一些常用的編輯,最後將編輯後的字串連線在一起進行合併。
常用字串操作
定義輸入文字後,將其拆分為單個單詞。文字拆分時以空格、換行符作為預設分隔符,使用split()方法可以將文字拆分為單個單詞,單詞中並不會出現空格、換行符或者其它指定的分隔符: ```python
input_text = 'Never regret falling in love with you. The longer you go, the more you cherish it. If time can flow back to the past, I must make a love song with you again, because you are the only one in my life.' words = input_text.split() words ['Never', 'regret', 'falling', 'in', 'love', 'with', 'you.', 'The', 'longer', 'you', 'go,', 'the', 'more', 'you', 'cherish', 'it.', 'If', 'time', 'can', 'flow', 'back', 'to', 'the', 'past,', 'I', 'must', 'make', 'a', 'love', 'song', 'with', 'you', 'again,', 'because', 'you', 'are', 'the', 'only', 'one', 'in', 'my', 'life.'] ```
用 “x
” 字元替換句子中出現的大寫字母。遍歷每個單詞的每個字元,對於每一個字元,如果它是一個大寫字母,則返回一個 “x
”。這一過程是通過兩個列表推導完成的,一個在列表上執行,另一個在每個單詞上執行,並通過條件語句進行判斷僅在字元為大寫字母時替換它們 —— 'x' if w.isupper() else w for w in word
,最後將這些字元使用 join()
方法連線在一起:
```python
replaced = [''.join('x' if w.isupper() else w for w in word) for word in words] replaced ['xever', 'regret', 'falling', 'in', 'love', 'with', 'you.', 'xhe', 'longer', 'you', 'go,', 'the', 'more', 'you', 'cherish', 'it.', 'xf', 'time', 'can', 'flow', 'back', 'to', 'the', 'past,', 'x', 'must', 'make', 'a', 'love', 'song', 'with', 'you', 'again,', 'because', 'you', 'are', 'the', 'only', 'one', 'in', 'my', 'life.']
對文字進行編碼,將文字轉換為純 `ASCII` 編碼格式,這在實際應用中十分重要,如果不進行合適的編碼,在顯示時會出現意料之外的錯誤。每個單詞都被編碼為 `ASCII` 位元組序列,然後再次解碼回 `Python` 字串型別,並且在轉換時使用 `errors` 引數來強制替換未知字元:
python ascii_text = [word.encode('ascii',errors='replace').decode('ascii') for word in replaced] ascii_text ['xever', 'regret', 'falling', 'in', 'love', 'with', 'you.', 'xhe', 'longer', 'you', 'go,', 'the', 'more', 'you', 'cherish', 'it.', 'xf', 'time', 'can', 'flow', 'back', 'to', 'the', 'past,', 'x', 'must', 'make', 'a', 'love', 'song', 'with', 'you', 'again,', 'because', 'you', 'are', 'the', 'only', 'one', 'in', 'my', 'life.']將單詞進行分組,並且每組最多有 `80` 個字元,每一組作為一行。為所有以句點結尾的單詞新增一個額外的換行符,作為不同組的標誌,之後建立一個新行並逐個新增單詞;如果一個行的單詞超過 `80` 個字元,則會結束該行並開始一個新行,同樣,當遇到一個換行符時,也會開始一個新行,我們還需要添加了一個額外的空格來分隔單詞:
python newlines = [word + '\n' if word.endswith('.') else word for word in ascii_text] newlines ['xever', 'regret', 'falling', 'in', 'love', 'with', 'you.\n', 'xhe', 'longer', 'you', 'go,', 'the', 'more', 'you', 'cherish', 'it.\n', 'xf', 'time', 'can', 'flow', 'back', 'to', 'the', 'past,', 'x', 'must', 'make', 'a', 'love', 'song', 'with', 'you', 'again,', 'because', 'you', 'are', 'the', 'only', 'one', 'in', 'my', 'life.\n'] line_size = 80 lines = [] line = '' for word in newlines: ... if line.endswith('\n') or len(line) + len(word) + 1 > line_size: ... lines.append(line) ... line = '' ... line = line + ' ' + word ```
最後,將每一行按照標題形式進行格式化(每個單詞的第一個字母大寫),並將它們連線為一段文字: ```python
lines = [line.title() for line in lines] result = ''.join(lines) print(result) Xever Regret Falling In Love With You. Xhe Longer You Go, The More You Cherish It. Xf Time Can Flow Back To The Past, X Must Make A Love Song With You Again, ```
其它字串操作
除了上述操作外,可以對字串執行的其他一些有用的操作。例如,字串可以像任何其他列表一樣使用切片,'love'[0:3]
將返回 lov
。類似於 title()
方法,可以使用 upper()
方法和 lower()
方法,可以分別用於返回字串的大寫和小寫版本:
```python
print('unicode'[0:3]) uni print('unicode'.upper()) UNICODE print('UNicode'.lower()) unicode ```
- OpenCV使用顏色進行膚色檢測
- Keras深度學習——構建電影推薦系統
- PyTorch張量操作詳解
- OpenCV直方圖的比較
- Python 常用字串操作
- 使用 dlib 進行人臉識別
- OpenCV 人臉檢測詳解(僅需2行程式碼學會人臉檢測)
- Keras深度學習——使用fastText構建單詞向量
- Keras深度學習——使用skip-gram和CBOW模型構建單詞向量
- Keras深度學習——從零開始構建單詞向量
- Keras深度學習——生成對抗網路
- Keras深度學習——建立自定義目標檢測資料集
- PyTorch強化學習——基於值迭代的強化學習演算法
- PyTorch強化學習——模擬FrozenLake環境
- PyTorch強化學習——策略評估
- PyTorch強化學習——馬爾科夫決策過程
- Keras深度學習——DeepDream演算法生成影象
- Keras深度學習——使用對抗攻擊生成可欺騙神經網路的影象
- PyTorch強化學習——策略梯度演算法
- Keras深度學習——交通標誌識別