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]
相关推荐
新手村领路人5 分钟前
opencv gpu cuda python c++版本测试代码
python·opencv·cuda
高洁0119 分钟前
大模型-高效优化技术全景解析:微调 量化 剪枝 梯度裁剪与蒸馏 下
人工智能·python·深度学习·神经网络·知识图谱
white-persist39 分钟前
CSRF 漏洞全解析:从原理到实战
网络·python·安全·web安全·网络安全·系统安全·csrf
Bellafu6661 小时前
本地搭建EXAM-MASTER考试系统
python
开心-开心急了1 小时前
Flask入门教程——李辉 第三章 关键知识梳理
后端·python·flask
rannn_1112 小时前
【学以致用|python自动化办公】OCR批量识别自动存为Excel(批量识别发票)
python·ocr·excel·财务
AI视觉网奇3 小时前
pycharm 默认终端设置 cmd
ide·python·pycharm
言之。3 小时前
LiteLLM:让LLM调用变得简单统一
后端·python·flask
ZhengEnCi3 小时前
Python_try-except-finally 完全指南-从异常处理到程序稳定的 Python 编程利器
后端·python
jarreyer3 小时前
常见分析方法与对应图表汇总
python·信息可视化·数据分析