You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现字符而非单词的长度限制遇阻,寻求技术帮助

字符数限制功能实现方案

原代码是用来移除单词末尾ed/ly/ing后缀的,和你要的字符数限制需求不匹配,下面给你两种实用的实现方案:

方案1:直接截断到指定字符数

不管单词是否被拆分,直接截取字符串的前N个字符:

test_str = 'Running the boy gladly jumped'
max_chars = 15  # 自定义你需要的最大字符数

# 执行截断
result = [test_str[:max_chars]]
print(result)
# 输出结果: ['Running the bo']

方案2:截断时保留完整单词

如果字符数限制刚好落在单词中间,自动截断到上一个完整单词的末尾,避免拆分单词:

test_str = 'Running the boy gladly jumped'
max_chars = 15

# 先截取到指定长度,再处理单词拆分问题
temp = test_str[:max_chars]
if len(test_str) > max_chars and not temp.endswith(' '):
    # 从后往前找第一个空格,截断到空格前
    result = [temp.rsplit(' ', 1)[0]]
else:
    result = [temp]

print(result)
# 输出结果: ['Running the']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:54:56