如何使用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
相关产品推荐
相关产品推荐

