简体   繁体   English

python的re.sub是否将数组作为输入参数?

[英]Does python's re.sub take an array as the input parameter?

According to http://www.php2python.com/wiki/function.preg-replace-callback/ re.sub is the python equivlant of PHP's preg_replace_callback, but the php version takes an array for the strings to be matched, so you can pass multiple strings, but the re.sub appears to take only a single string. 根据http://www.php2python.com/wiki/function.preg-replace-callback/ re.sub是PHP的preg_replace_callback的python等价物,但php版本需要一个数组来匹配字符串,所以你可以传递多个字符串,但re.sub似乎只接受一个字符串。

Is that right or is it my weak knowledge of python? 这是对的还是我对python的微弱知识?

If you want to do it on an array, you can use a list comprehension, eg 如果要在数组上执行此操作,可以使用列表推导,例如

>>> array_of_strings = ["3a1", "1b2", "1c", "d"]
>>> [re.sub("[a-zA-Z]", "", elem) for elem in array_of_strings]
["31", "12", "1", ""]

though if you're using a complicated expression, you should probably use re.compile on the pattern first 虽然如果你使用的是复杂的表达式,你应该首先在模式上使用re.compile

Late to the party I know, but if this was a requirement for a many step process you wanted to encapsulate into a function, then you could process through numpy vectorize: 在我认识的派对上,但如果这是一个需要多步骤过程的要求,你想要封装到一个函数中,那么你可以通过numpy vectorize进行处理:

def EliminateAlpha(elem):
    return re.sub("[a-zA-Z]", "", elem)

ElimAlphaArray = np.vectorize(ElimateAlpha)

array_of_strings = ["3a1", "1b2", "1c", "d"]
print(ElimAlphaArray(array_of_strings))

['31' '12' '1' '']

Of course, you can use the re.sub function directly into vectorize: 当然,您可以将re.sub函数直接用于vectorize:

ElimAlphaArr = np.vectorize(re.sub)
print(ElimAlphaArr("[a-zA-Z]", "", array_of_strings))

['31' '12' '1' '']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM