Python之標(biāo)點(diǎn)符號(hào)string.punctuation的使用
Python標(biāo)點(diǎn)符號(hào)string.punctuation
在Python中,string
模塊包含了一些用于處理字符串的常量和方法。其中,string.punctuation
是一個(gè)字符串,它包含了所有的ASCII標(biāo)點(diǎn)符號(hào)字符。
string.punctuation
的值如下:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
這個(gè)字符串包含了所有常見的標(biāo)點(diǎn)符號(hào),例如感嘆號(hào)、引號(hào)、括號(hào)、逗號(hào)、冒號(hào)、分號(hào)、問號(hào)、@符號(hào)、方括號(hào)、大括號(hào)、波浪線等。
如果你想要檢查一個(gè)字符是否是標(biāo)點(diǎn)符號(hào),你可以使用 in
關(guān)鍵字來檢查這個(gè)字符是否在 string.punctuation
中:
import string char = "!" if char in string.punctuation: print(f"{char} 是一個(gè)標(biāo)點(diǎn)符號(hào)") else: print(f"{char} 不是一個(gè)標(biāo)點(diǎn)符號(hào)")
輸出:
! 是一個(gè)標(biāo)點(diǎn)符號(hào)
這樣,你就可以使用 string.punctuation
來識(shí)別和處理字符串中的標(biāo)點(diǎn)符號(hà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 #所有的十六進(jìn)制字符 '0123456789abcdefABCDEF' >>> string.whitespace #所有的空白字符 ' \t\n\r\x0b\x0c' >>> string.punctuation #所有的標(biāo)點(diǎn)字符 '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
常用標(biāo)點(diǎn)符號(hào)
punctuation = ['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
統(tǒng)計(jì)一個(gè)文件或一個(gè)字符串中所有單詞出現(xiàn)的次數(shù)。由于句子中存在標(biāo)點(diǎn)符號(hào),直接對(duì)字符串切割的話會(huì)把單詞和標(biāo)點(diǎn)切割在一起。
為了避免這個(gè)問題,我們可以先把句子中的標(biāo)點(diǎn)符號(hào)統(tǒng)一替換為空格,然后在split()切割即可搞定。
這時(shí)候就可以用上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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
純numpy數(shù)值微分法實(shí)現(xiàn)手寫數(shù)字識(shí)別
本文主要介紹了純numpy數(shù)值微分法實(shí)現(xiàn)手寫數(shù)字識(shí)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08

Python+Appium實(shí)現(xiàn)自動(dòng)搶微信紅包

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

Python 從subprocess運(yùn)行的子進(jìn)程中實(shí)時(shí)獲取輸出的例子

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