Skip to main content
 首页 » 编程设计

python之tbl = str.maketrans({ord(ch) :""for ch in punctuation}) 是什么意思

2024年10月24日7del

这是完整的代码:

s = 'life is short, stunt it!!?' 
from string import punctuation 
tbl = str.maketrans({ord(ch):" " for ch in punctuation}) 
print(s.translate(tbl).split()) 

我想知道 tbl = str.maketrans({ord(ch):""for ch in punctuation}) 在此代码中或一般情况下是什么意思?

请您参考如下方法:

它构建一个标点字符到空格的字典,翻译字符串(有效地删除标点符号),然后在空格处拆分以生成单词列表。

逐步...首先构建一个字符翻译词典,其中键是标点符号,替换字符是空格。这使用字典理解来构建字典:

from string import punctuation 
s = 'life is short, stunt it!!?' 
D = {ord(ch):" " for ch in punctuation} 
print(D) 

结果:

{64: ' ', 124: ' ', 125: ' ', 91: ' ', 92: ' ', 93: ' ', 94: ' ', 95: ' ', 96: ' ', 33: ' ', 34: ' ', 35: ' ', 36: ' ', 37: ' ', 38: ' ', 39: ' ', 40: ' ', 41: ' ', 42: ' ', 43: ' ', 44: ' ', 45: ' ', 46: ' ', 47: ' ', 123: ' ', 126: ' ', 58: ' ', 59: ' ', 60: ' ', 61: ' ', 62: ' ', 63: ' '} 

这一步是多余的。虽然字典看起来不同,但字典是无序的,键和值是相同的。 maketrans 可以根据 translate 的要求将字符键转换为序数值,但这在创建字典时已经完成。它还有此处未使用的其他用例,因此可以删除 maketrans。

tbl = str.maketrans(D) 
print(tbl) 
print(D == tbl) 

结果:

{64: ' ', 60: ' ', 61: ' ', 91: ' ', 92: ' ', 93: ' ', 94: ' ', 95: ' ', 96: ' ', 33: ' ', 34: ' ', 35: ' ', 36: ' ', 37: ' ', 38: ' ', 39: ' ', 40: ' ', 41: ' ', 42: ' ', 43: ' ', 44: ' ', 45: ' ', 46: ' ', 47: ' ', 59: ' ', 62: ' ', 58: ' ', 123: ' ', 124: ' ', 125: ' ', 126: ' ', 63: ' '} 
True 

现在进行翻译:

s = s.translate(tbl) 
print(s) 

结果:

life is short  stunt it    

拆分为单词列表:

print(s.split()) 

结果:

['life', 'is', 'short', 'stunt', 'it']