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

Python脚本计算单词one间距异常:非开头场景结果错误排查

问题排查与修正:计算连续one之间的单词间距

问题根源

你的代码错误将文本起始到第一个one的单词间距纳入结果,原因是striped_long_text.split('one')返回的列表中,第一个元素就是文本开头到第一个one的片段,而原代码遍历了所有片段,导致多统计了无关内容。

修正后的代码

import re

# dummy text
words_list = ['one']
long_string = "are marked by one  the ()meta-characters. two They group together the expressions contained one inside them, and you can one repeat the contents of a group with a repeating qualifier, such as there one"

striped_long_text = re.sub(' +', ' ', (long_string.replace('\n', ' '))).strip()
length = []

for item in words_list:
    text_split = striped_long_text.split(item)[:-1]
    # 跳过文本开头到第一个one的片段,只处理连续one之间的内容
    for space in text_split[1:]:
        if space:
            length.append(space.count(' ') - 1)

print(length)  # 输出: [9, 5, 13]

关键修改说明

仅需将遍历text_split的范围从全部元素改为text_split[1:],跳过第一个无关片段,即可精准统计每两个连续one之间的单词数量(通过空格数减1计算)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 12:06:27