You need to enable JavaScript to run this app. TensorFlow 2中如何按任意标点和空白字符拆分字符串
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow 2中如何按任意标点和空白字符拆分字符串

解决方案

错误原因

  • tf.strings.split的sep参数默认按任意空白拆分,但显式传入字符串时仅做字面精确匹配,不识别正则规则,所以你写的\W-_.,不会按预期匹配多种分隔符
  • 原分隔符规则覆盖不全,也没有处理连续分隔符的逻辑

正确实现方式

方案1:直接使用正则拆分(推荐,TensorFlow 1.15及以上版本支持)

使用tf.strings.regex_split直接传入正则匹配规则,一次性完成拆分:

import tensorflow as tf

# 示例输入张量
t = tf.constant(["Hello,world!  this is a test-string 123_abc", "Another example:with.punctuation and  multiple   spaces"])

# 规则说明:
# \s 匹配所有空白字符(空格、制表符、换行等)
# \p{P} 匹配所有Unicode标点符号
# + 表示匹配连续1个及以上的分隔符,自动合并连续分隔符避免拆分出空串
t_split = tf.strings.regex_split(t, pattern=r"[\s\p{P}]+")

运行后输出的拆分结果示例:

<tf.RaggedTensor [[b'Hello', b'world', b'this', b'is', b'a', b'test', b'string', b'123', b'abc'], [b'Another', b'example', b'with', b'punctuation', b'and', b'multiple', b'spaces']]>

方案2:兼容旧版本的替换后拆分方案

如果你的TensorFlow版本较低没有regex_split接口,可以先把所有分隔符统一替换为单个空格,再按默认规则拆分:

# 第一步:把所有连续的标点/空白替换为单个空格
t_replaced = tf.strings.regex_replace(t, r"[\s\p{P}]+", " ")
# 第二步:按空白拆分,自动忽略首尾空格和连续空格
t_split = tf.strings.split(t_replaced)

两种方案效果完全一致,都能满足按任意标点、空白(含连续空白)拆分的需求。

内容的提问来源于stack exchange,提问作者stats_b

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 20:18:02