需求:
编写一个程序,输入一段英文句子,统计每个单词的长度,并将单词按照长度从短到长排序。
程序逻辑框图
1、用户输入一句英文句子。
2、对输入的句子进行预处理(去空格并分割为单词列表)。
3、统计每个单词的长度。
4、按照单词长度排序。
5、输出结果。
代码实现:
def process_sentence(sentence):
"""
处理英文句子,统计每个单词长度并按照长度排序。
参数:
sentence (str): 输入的英文句子
返回:
list: 按长度排序的单词列表,每个元素为 (单词, 长度)
"""
# 去除两端多余空格并按空格分割句子为单词
words = sentence.strip().split()
# 生成包含单词及其长度的元组列表
word_lengths = [(word, len(word)) for word in words]
# 按长度排序单词
sorted_words = sorted(word_lengths, key=lambda x: x[1])
return sorted_words
# 测试
if __name__ == "__main__":
# 用户输入句子
input_sentence = input("请输入一个英文句子: ")
# 调用函数处理句子
result = process_sentence(input_sentence)
# 输出结果
print("\n每个单词及其长度(按长度排序):")
for word, length in result:
print(f"单词: {word}, 长度: {length}")
使用类(class)实现该功能:
程序逻辑框图
类定义:
init: 初始化对象,存储输入句子。
process_sentence: 分割句子并生成单词和长度的元组列表。
sort_by_length: 按单词长度对元组列表排序。
测试代码:
1、用户输入句子。
2、创建 SentenceProcessor 类实例。
3、调用方法获取排序后的单词及长度。
4、输出结果。
代码实现:
class SentenceProcessor:
"""
英文句子处理类,用于统计单词长度并按照长度排序。
"""
def __init__(self, sentence):
"""
初始化对象,存储句子。
参数:
sentence (str): 输入的英文句子
"""
self.sentence = sentence.strip()
self.words = []
def process_sentence(self):
"""
处理句子,将单词及其长度存储为列表。
返回:
list: 包含 (单词, 长度) 的元组列表
"""
# 分割句子为单词
self.words = self.sentence.split()
# 生成包含单词和长度的元组列表
return [(word, len(word)) for word in self.words]
def sort_by_length(self):
"""
按单词长度排序。
返回:
list: 按长度排序的 (单词, 长度) 的元组列表
"""
# 调用 process_sentence 方法生成元组
word_lengths = self.process_sentence()
# 按长度排序
return sorted(word_lengths, key=lambda x: x[1])
# 测试
if __name__ == "__main__":
# 用户输入句子
input_sentence = input("请输入一个英文句子: ")
# 创建处理器对象
processor = SentenceProcessor(input_sentence)
# 获取排序结果
sorted_words = processor.sort_by_length()
# 输出结果
print("\n每个单词及其长度(按长度排序):")
for word, length in sorted_words:
print(f"单词: {word}, 长度: {length}")