TensorFlow 字符串操作

目录

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

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

示例 1:字符串拼接

python 复制代码
import tensorflow as tf

# 创建字符串张量
tensor1 = tf.constant(["Hello", "TensorFlow"])
tensor2 = tf.constant(["World", "Strings"])

# 拼接字符串
result = tf.strings.join([tensor1, tensor2], separator=" ")
print(result.numpy())  

结果如下:

powershell 复制代码
[b'Hello World' b'TensorFlow Strings']

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

示例 2:字符串分割

python 复制代码
import tensorflow as tf

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

结果如下:

powershell 复制代码
[b'apple' b'banana' b'orange']

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

python 复制代码
import tensorflow as tf

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

结果如下:

powershell 复制代码
[b'HELLO' b'TENSORFLOW']

示例 4:字符串长度

python 复制代码
import tensorflow as tf

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

结果如下:

powershell 复制代码
[ 4 10]

示例 5:正则匹配

python 复制代码
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]

结果如下:

powershell 复制代码
[ True False]
相关推荐
景彡先生16 小时前
Python Selenium详解:从入门到实战,Web自动化的“瑞士军刀”
前端·python·selenium
珺毅同学18 小时前
YOLO输出COCO指标及YOLOv12报错
python·深度学习·yolo
2401_8414956420 小时前
Windows 系统中ffmpeg安装问题的彻底解决
windows·python·ffmpeg·bug·语音识别·下载·安装步骤
waysolong9020 小时前
MCP服务构建、使用
python
胜天半月子21 小时前
Python自动化测试 | 快速认识并了解pytest的基本使用
服务器·python·pytest
小小测试开发21 小时前
Python Web3库入门:从零开始与以太坊区块链交互
python·web3·区块链
独行soc21 小时前
2025年渗透测试面试题总结-224(题目+回答)
网络·python·安全·web安全·adb·渗透测试·安全狮
程序员三藏21 小时前
软件测试之环境搭建及测试流程
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
10岁的博客21 小时前
PyTorch快速搭建CV模型实战
人工智能·pytorch·python
寒秋丶1 天前
AutoGen多智能体协作、人机交互与终止条件
人工智能·python·microsoft·ai·人机交互·ai编程·ai写作