numpy字符串操作 |翻译()函数
numpy.core.defchararray.translate(arr, table, deletechars=None)
是另一个在 numpy 中进行字符串操作的函数。对于 arr 中的每个元素,它返回字符串的副本,其中删除了可选参数deletechars中出现的所有字符,其余字符已通过给定的转换表映射。如果有多个值要翻译,则将字典传递给 maketrans函数以创建翻译表。
Parameters:
arr : array_like of str or unicode.Input array.
table : Translate mapping specified to perform translations.
deletechars : String type, characters to be deleted.
Returns : [ndarray] Output array of str or unicode with translated values.
代码#1:
# Python program explaining
# numpy.core.defchararray.translate() method
# importing numpy
import numpy as geek
# input array
in_arr = geek.array(['Weeks', 'our', 'Weeks'])
print ("Input original array : ", in_arr)
# creating dictionary for translation table
trans_dict ={"W": "G", "o": "f", "u": "o"}
# creating translation table from dictionary
trans_table ="Wou".maketrans(trans_dict)
out_arr = geek.core.defchararray.translate(in_arr, trans_table, deletechars ="None")
print ("Output translated array: ", out_arr)
输出:
Input original array : ['Weeks' 'our' 'Weeks']
Output translated array: ['Geeks' 'for' 'Geeks']