本文共 1214 字,大约阅读时间需要 4 分钟。
为了解决这个问题,我们需要编写一个Python程序来统计一段英文文本中的所有不同单词,并找出词频最大的前10%的单词。以下是详细的解决方案。
#符号。import systext = sys.stdin.read().strip('#')# 替换非法字符为空格,并将所有字符转换为小写processed = []for c in text: if c.isalnum() or c == '_': processed.append(c.lower()) else: processed.append(' ')text = ''.join(processed).strip()# 分割单词words = text.split()# 截断超过15个字符的单词for i in range(len(words)): if len(words[i]) > 15: words[i] = words[i][:15]# 统计单词频率word_counts = {}for word in words: word_counts[word] = word_counts.get(word, 0) + 1# 按词频降序和字典序升序排序sorted_words = sorted(word_counts.items(), key=lambda x: (-x[1], x[0]))# 输出结果print(len(sorted_words))num_to_output = int(len(sorted_words) / 10)for i in range(num_to_output): print(f"{sorted_words[i][1]}:{sorted_words[i][0]}") sys.stdin.read()读取所有输入内容,并去掉末尾的#符号。转载地址:http://dbii.baihongyu.com/