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]
相关推荐
Csvn1 天前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch89181 天前
Python主流框架全解析
开发语言·python
sg_knight1 天前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财1 天前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張4081 天前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_423533991 天前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz2 天前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据2 天前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby2 天前
springboot读取配置文件
后端·python·flask
阿Y加油吧2 天前
回溯法经典难题:N 皇后问题 深度解析 + 二分查找入门(搜索插入位置)
开发语言·python