首页 > 解决方案 > 正则表达式将数字字符串替换为字符串

问题描述

有一个数字字符串的张量(如“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: int() 以 10 为底的无效文字:'\1'

标签: pythontensorflow

解决方案


我认为您无法使用 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']

推荐阅读