Python之標(biāo)點符號string.punctuation的使用
Python標(biāo)點符號string.punctuation
在Python中,string
模塊包含了一些用于處理字符串的常量和方法。其中,string.punctuation
是一個字符串,它包含了所有的ASCII標(biāo)點符號字符。
string.punctuation
的值如下:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
這個字符串包含了所有常見的標(biāo)點符號,例如感嘆號、引號、括號、逗號、冒號、分號、問號、@符號、方括號、大括號、波浪線等。
如果你想要檢查一個字符是否是標(biāo)點符號,你可以使用 in
關(guān)鍵字來檢查這個字符是否在 string.punctuation
中:
import string char = "!" if char in string.punctuation: print(f"{char} 是一個標(biāo)點符號") else: print(f"{char} 不是一個標(biāo)點符號")
輸出:
! 是一個標(biāo)點符號
這樣,你就可以使用 string.punctuation
來識別和處理字符串中的標(biāo)點符號了。
妙用string.punctuation
>>> import string >>> dir(string) ['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__built ins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__packag e__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_u ppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctua tion', 'whitespace'] >>> string.ascii_lowercase #所有的小寫字母 'abcdefghijklmnopqrstuvwxyz' >>> string.ascii_uppercase #所有的大寫字母 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.hexdigits #所有的十六進制字符 '0123456789abcdefABCDEF' >>> string.whitespace #所有的空白字符 ' \t\n\r\x0b\x0c' >>> string.punctuation #所有的標(biāo)點字符 '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
常用標(biāo)點符號
punctuation = ['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
統(tǒng)計一個文件或一個字符串中所有單詞出現(xiàn)的次數(shù)。由于句子中存在標(biāo)點符號,直接對字符串切割的話會把單詞和標(biāo)點切割在一起。
為了避免這個問題,我們可以先把句子中的標(biāo)點符號統(tǒng)一替換為空格,然后在split()切割即可搞定。
這時候就可以用上string.punctuation
import string #注意使用前要先將string模塊導(dǎo)入 def read_file(txt): # txt為文件名 for c in string.punctuation: txt = txt.replace(c,' ') return txt.split
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
純numpy數(shù)值微分法實現(xiàn)手寫數(shù)字識別
本文主要介紹了純numpy數(shù)值微分法實現(xiàn)手寫數(shù)字識別,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08

在django中查詢獲取數(shù)據(jù),get, filter,all(),values()操作

Python 從subprocess運行的子進程中實時獲取輸出的例子

python 使用cycle構(gòu)造無限循環(huán)迭代器