正则表达式替换数字为字母串

2024-09-29 00:21:59 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个由数字串组成的张量(比如“32”、“45”等等),我怎么能把它转换成一个张量,这个张量有一个符号重复的次数和数字所表示的次数一样多。你知道吗

例如,如果我有一个张量[“2”,“3”,“0”,“1”],我想得到像[“aa”,“aaa”,“a”]。你知道吗

我已经使用numpy获得了它,但是现在我正在尝试直接在TensorFlow中完成它,因为我没有启动会话,所以我无法查找变量值。你知道吗

我在这里分享一段代码

import tensorflow as tf

a = tf.Variable(["2", "3", "0", "1"], dtype=tf.dtypes.string)
res = tf.strings.regex_replace(a, "([0-9]+)", r"a" * int("\\1"))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(res)) # It should show ["aa", "aaa", "", "a"]

但是int(“\1”)不返回数字,而是返回ValueError:

ValueError:基为10的int()的文本无效:'\1'


Tags: runnumpytftensorflowas符号res数字
1条回答
网友
1楼 · 发布于 2024-09-29 00:21:59

我不认为用TensorFlow中的正则表达式可以做到这一点。有一种方法可以做到:

import tensorflow as tf

def repeat_symbol(nums, symbol):
    nums = tf.convert_to_tensor(nums)
    symbol = tf.convert_to_tensor(symbol)
    # Make sequence mask from numbers
    mask = tf.sequence_mask(nums)
    # Use sequence mask to pick either the symbol or an empty string
    symbol_rep = tf.gather(tf.stack(["", symbol]), tf.cast(mask, tf.int32))
    # Join result
    return tf.strings.reduce_join(symbol_rep, axis=-1)

with tf.Graph().as_default(), tf.Session() as sess:
    a = tf.constant(["2", "3", "0", "1"], dtype=tf.string)
    # Convert strings to numbers
    a_nums = tf.strings.to_number(a, out_type=tf.int32)
    result = repeat_symbol(a_nums, "a")
    print(sess.run(result))
    # [b'aa' b'aaa' b'' b'a']

相关问题 更多 >