我希望识别列表中的任何字符串是否在任何位置都包含数字/数字,如果是,那么代码应该使用python从字符串中删除该数字。我的代码是
pattern = '\w+-\w+[-\w+]*|-';
pattern2 = '\d'
contents = ["babies","walked","boys","walking", "CD28", "IL-2", "honour"];
for token in contents:
if token.endswith("ies"):
f.write(string.replace(token,'ies','y',1))
elif token.endswith('s'):
f.write(token[0:-1])
elif token.endswith("ed"):
f.write(token[0:-2])
elif token.endswith("ing"):
f.write(token[0:-3])
elif re.match(pattern,token):
f.write(string.replace(token,'-',""))
elif re.match(pattern2,token):
f.write(token.translate(None,"0123456789"))
else:
f.write(t)
f.close()实际上,问题在re.match(patter2,token)中。它不能识别一个数字作为标记,但是当我单独使用它时,f.write(token.translate(None,"0123456789"))工作得很好。
发布于 2015-04-01 10:47:53
您只需在列表理解中使用re.sub:
>>> contents = ["IL-2", "CD-28","IL2","25"]
>>> import re
>>> [re.sub(r'\d','',i) for i in contents]
['IL-', 'CD-', 'IL', '']但是,作为一个更好的解决方案,您可以使用str.translate方法!
>>> from string import digits
>>> [i.translate(None,digits) for i in contents]
['IL-', 'CD-', 'IL', '']如果你在python 3:
>>> trans_table = dict.fromkeys(map(ord,digits), None)
>>> [i.translate(trans_table) for i in contents]
['IL-', 'CD-', 'IL', '']发布于 2015-04-01 10:47:50
如果要删除数字,请使用str.translate
contents = ["IL-2", "CD-28","IL2","25"];
print([s.translate(None,"0123456789") for s in contents])
['IL-', 'CD-', 'IL', '']如果只想删除字符串包含混合的数字,则为:
print([s.translate(None,"0123456789") if not s.isdigit() else s for s in contents])
['IL-', 'CD-', 'IL', '25']如果数字总是在末尾,则可以使用rstrip:
print([s.rstrip("0123456789") for s in contents])对于python 3,您需要使用str.maketrans创建一个表
tbl = str.maketrans({k:"" for k in dig})
print([s.translate(tbl) for s in contents])
['IL-', 'CD-', 'IL', '']https://stackoverflow.com/questions/29388759
复制相似问题