python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python标点符号string.punctuation

Python之标点符号string.punctuation的使用

作者:Covirtue

Python的string模块提供了一个方便的属性string.punctuation,其中包含所有ASCII标点符号字符,这使得在处理和识别字符串中的标点符号时非常有用,可以通过简单的in关键字来检测字符是否为标点

Python标点符号string.punctuation

在Python中,string 模块包含了一些用于处理字符串的常量和方法。其中,string.punctuation 是一个字符串,它包含了所有的ASCII标点符号字符。

string.punctuation 的值如下:

'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

这个字符串包含了所有常见的标点符号,例如感叹号、引号、括号、逗号、冒号、分号、问号、@符号、方括号、大括号、波浪线等。

如果你想要检查一个字符是否是标点符号,你可以使用 in 关键字来检查这个字符是否在 string.punctuation 中:

import string

char = "!"
if char in string.punctuation:
    print(f"{char} 是一个标点符号")
else:
    print(f"{char} 不是一个标点符号")

输出:

! 是一个标点符号

这样,你就可以使用 string.punctuation 来识别和处理字符串中的标点符号了。

妙用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      #所有的标点字符
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

常用标点符号

punctuation = ['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']

统计一个文件或一个字符串中所有单词出现的次数。由于句子中存在标点符号,直接对字符串切割的话会把单词和标点切割在一起。

为了避免这个问题,我们可以先把句子中的标点符号统一替换为空格,然后在split()切割即可搞定。

这时候就可以用上string.punctuation

import string    #注意使用前要先将string模块导入
def read_file(txt):  # txt为文件名
    for c in string.punctuation:
        txt = txt.replace(c,' ')
return txt.split

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文