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]
相关推荐
菜鸡儿齐2 小时前
Unsafe方法学习
java·python·学习
老师好,我是刘同学5 小时前
Python执行命令并保存输出到文件
python
啵啵鱼爱吃小猫咪7 小时前
机械臂阻抗控制github项目-mujoco仿真
开发语言·人工智能·python·机器人
MaximusCoder7 小时前
等保测评命令——Centos Linux
linux·运维·经验分享·python·安全·centos
yunyun321237 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
m0_662577977 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
songyuc7 小时前
【PyTorch】感觉`CrossEntropyLoss`和`BCELoss`很类似,为什么它们接收labels的shape常常不一样呢?
人工智能·pytorch·python
ℳ๓₯㎕.空城旧梦8 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python
浩子智控9 小时前
python程序打包的文件地址处理
开发语言·python·pyqt
Jackey_Song_Odd9 小时前
Part 1:Python语言核心 - 序列与容器
开发语言·windows·python