python3 中关于translate删除特定字符的问题

来源:4-6 如何去掉字符串中不需要的字符

qq_上帝的私语_0

2017-04-21

s = "abc\refg\n23452\t"

# 该方法在python3中报错
# TypeError: first maketrans argument must be a string if there is a second argument
# str_trans = str.maketrans(None, '\r\t\n') # 报错

str_trans = str.maketrans("   ", '\r\t\n') # 这样好像是可行的?
print(s.translate(str_trans))

u= u"abc中eg"
# 还是: abc中eg
print(u.translate({u"中":None}))
# 还是: abc中eg
print(u.translate(dict.fromkeys([u"中",u"文"])))


str.maketrans(None, '\r\t\n')在python3中好像是有问题,替换成 str.maketrans("   ", '\r\t\n') 是否可行,试过好像是没问题,但不确定是否有坑

print(u.translate({u"中":None}))     print(u.translate(dict.fromkeys([u"中",u"文"]))) # 这两句就不起作用了

写回答

2回答

Billy2017

2017-12-23

import unicodedata,sys

u = 'èěéēàǎā'

# 首先在python3中无法通过shell得知组合字符的ASCII~
# 首先使用unicodedata.normalize() 将原始输入标准化为分解形式字符
a = unicodedata.normalize('NFD',u)

# 通过使用dict.fromkeys() 方法构造一个字典,每个Unicode和音调作为键,对应的值全部为None
# sys.maxunicode : 给出最大Unicode代码点的值的整数,即1114111(十六进制的0x10FFFF)。
# unicodedata.combining:将分配给字符chr的规范组合类作为整数返回。如果未定义组合类,则返回0
# 这样我们就成功将所有组合类的值全部设置为None
cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c)))

# 再调用translate函数删除所有音调~
print(a.translate(cmb_chrs))

另外,python3中对str的删除也做了改变,建议使用以下方法:

s = 'abc\rdef\nxyz\t'

# 在第三个参数处直接填入要删除的字符
str_trans = str.maketrans('','','\r\n\t')

print(s.translate(str_trans))


1
1
qq_上帝的私语_0
非常感谢!
2017-12-30
共1条回复

慕粉1443061649

2017-04-23

你可以看下py3关于translate的源码,我这边用py3.5也是这样,

源码里只保留了table这个2参数
def translate(self, table): # real signature unknown; restored from __doc__
   """
   S.translate(table) -> str
   
   Return a copy of the string S in which each character has been mapped
   through the given translation table. The table must implement
   lookup/indexing via __getitem__, for instance a dictionary or list,
   mapping Unicode ordinals to Unicode ordinals, strings, or None. If
   this operation raises LookupError, the character is left untouched.
   Characters mapped to None are deleted.
   """
   return ""

0
0

Python高效编程技巧实战

精选50个Python案例,源自实战,全面提升Python编程能力

2582 学习 · 360 问题

查看课程