如何在 Python 中去除字串中的所有標點符號?


在 Python 中去除字串中的所有標點符號可以透過多種方法實現。以下是一些示例

使用 string.punctuation

示例

string.punctuation 常量包含所有 ASCII 標點符號字元。我們可以使用此常量從字串中刪除所有標點符號字元。

我們使用列表推導式迭代字串中的每個字元,並檢查它是否不在 string.punctuation 常量中。如果不是標點符號字元,則將其新增到 no_punct 變數中。

import string
# sample string with punctuation
text = "Lorem, Ipsum!!!"
# remove punctuation
no_punct = "".join(char for char in text if char not in string.punctuation)
print(no_punct)

輸出

Lorem Ipsum

使用正則表示式

我們還可以使用正則表示式從字串中刪除所有標點符號字元。

示例

我們使用 re.sub() 方法將所有非單詞字元和非空格字元替換為空字串。

import re

# sample string with punctuation
text = "Lorem, Dolor!!!"

# remove punctuation using regular expression
no_punct = re.sub(r'[^\w\s]', '', text)

print(no_punct)

輸出

Lorem Dolor

使用 translate()

translate() 方法也可用於從字串中刪除標點符號。

示例

我們使用 str.maketrans() 方法建立一個轉換表,並將其傳遞給 translate() 方法以從字串中刪除表中的所有字元。

import string
# sample string with punctuation
text = "Lorem, Ipsum!!!"
# create a translation table
table = str.maketrans('', '', string.punctuation)
# remove punctuation
no_punct = text.translate(table)
print(no_punct)

輸出

Lorem Ipsum

以下是一些關於如何在 Python 中去除字串中所有標點符號的更多示例

使用迴圈迭代字元

我們還可以遍歷字串中的每個字元並刪除任何標點符號字元。

示例

我們遍歷字串中的每個字元,並檢查它是否是字母數字(字母或數字)或空格字元。如果是,則將其新增到 no_punct 變數中。這樣,我們就可以從結果字串中排除任何標點符號字元。

# sample string with punctuation
text = "Foo, Bar!!!"
# remove punctuation using a loop
no_punct = ""
for char in text:
    if char.isalnum() or char.isspace():
        no_punct += char
print(no_punct)

輸出

Foo Bar

使用 replace() 方法

我們還可以使用 replace() 方法從字串中刪除所有標點符號字元。

示例

我們使用 replace() 方法將每個標點符號字元(句號、逗號、感嘆號和問號)替換為空字串。這樣,我們就可以從字串中刪除所有標點符號字元。

# sample string with punctuation
text = "Fubar, Quz!!!"
# remove punctuation using the replace() method
no_punct = text.replace(".", "").replace(",", "").replace("!", "").replace("?", "")
print(no_punct)

輸出

Fubar Quz

使用 re 模組和標點符號字元列表

我們還可以使用 re 模組使用標點符號字元列表從字串中刪除所有標點符號字元。

示例

我們使用 re.sub() 方法將不是字母、數字或空格的字元替換為空字串。正則表示式 [^a−zA−Z0−9\s]+ 匹配任何不是字母、數字或空格的字元。

import re
# sample string with punctuation
text = "Foobar, Baz?"
# remove punctuation using the re module and a list of punctuation characters
no_punct = re.sub('[^a-zA-Z0-9\s]+', '', text)
print(no_punct)

輸出

Foobar Baz

更新於: 2023年8月11日

1K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.