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: int() 以 10 为底的无效文字:'\1'
解决方案
我认为您无法使用 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']
推荐阅读
- python - 如何从 div 标签中获取文本
- javascript - 未捕获的 ReferenceError:未使用 React 和 babel 定义模块
- sapui5 - 如何正确使用新的异步片段加载
- r - dnorm() 如何在 sapply 循环中处理分位数向量
- c# - 复制到另一个文本文件时如何覆盖或跳过特定行
- r - 如何将一系列日期更改为一个日期 R?
- python - 我正在尝试使用 def 对性别 = 男性和性别 = 女性的数据框进行有条件的添加
- bing-maps - 有没有办法对 bingmap 的信息框关闭按钮进行编程?
- mysql - 如何使用内部连接查询和 where like 子句从表 Produto_precos 中获取另外两个值
- javascript - 检查当前页面上是否存在数组中的任何类并使用 jQuery 将匹配的类保存为变量