欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > TensorFlow 字符串操作

TensorFlow 字符串操作

2025/4/9 12:38:45 来源:https://blog.csdn.net/weixin_43597208/article/details/146946641  浏览:    关键词:TensorFlow 字符串操作

目录

  • 示例 1:字符串拼接
  • 示例 2:字符串分割
  • 示例 3:字符串大小写转换
  • 示例 4:字符串长度
  • 示例 5:正则匹配

TensorFlow 提供了 tf.strings 模块,支持常见的字符串操作:

示例 1:字符串拼接

import tensorflow as tf# 创建字符串张量
tensor1 = tf.constant(["Hello", "TensorFlow"])
tensor2 = tf.constant(["World", "Strings"])# 拼接字符串
result = tf.strings.join([tensor1, tensor2], separator=" ")
print(result.numpy())  

结果如下:

[b'Hello World' b'TensorFlow Strings']

备注:b’…’ 表示 Python 中的字节字符串(而非 Unicode 字符串)。

示例 2:字符串分割

import tensorflow as tftext = tf.constant("apple,banana,orange")
split_result = tf.strings.split(text, sep=",")
print(split_result.numpy()) 

结果如下:

[b'apple' b'banana' b'orange']

示例 3:字符串大小写转换

import tensorflow as tf# 转换为大写
text = tf.constant(["hello", "TensorFlow"])
upper = tf.strings.upper(text)
print(upper.numpy())

结果如下:

[b'HELLO' b'TENSORFLOW']

示例 4:字符串长度

import tensorflow as tf# 计算字符串长度(按字节)
text = tf.constant(["深度学习", "TensorFlow"])
length = tf.strings.length(text, unit="UTF8_CHAR")  # 按字符计算
print(length.numpy())

结果如下:

[ 4 10]

示例 5:正则匹配

import tensorflow as tf# 检查是否匹配正则表达式
text = tf.constant(["2023-01-01", "股票代码:600519"])
pattern = r"\d{4}-\d{2}-\d{2}"  # 匹配日期格式
matches = tf.strings.regex_full_match(text, pattern)
print(matches.numpy())  # 输出:[ True False]

结果如下:

[ True False]

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词