You need to enable JavaScript to run this app. 如何使用Python统计文件中每个句子的单词数量
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python统计文件中每个句子的单词数量

对应方法说明

C# 中的 TrimEnd('.') 方法,在 Python 中直接用字符串的 rstrip('.') 方法即可完全替代,二者作用都是移除字符串末尾所有匹配的指定字符。

完整实现代码

sentences = "hello how are you. I am good. that's good."
# 移除末尾多余句号后按句号拆分句子
for raw_sent in sentences.rstrip('.').split('.'):
    sent = raw_sent.strip()
    word_num = len(sent.split())
    # 格式化对齐输出
    print(f"{sent}.".ljust(22) + f"{word_num} words;")

输出结果

运行代码后可完全匹配预期效果:

hello how are you.   4 words;
I am good.           3 words;
that's good.         2 words;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 21:15:04