酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

编写程序创建一个txt文件,写入“life was like a box of chocolates, you never know what you‘re going to get.”,并统计文本中单词出现的频率,按字母a-z顺序对键进行排序后输出。 提示:文件读写,字典,排序sorted,格式控制format

以下是使用Python编写的程序,可以创建一个txt文件,写入指定的文本,并统计文本中单词出现的频率。然后按字母a-z的顺序对单词进行排序,并按照指定的格式进行输出。 ```python import string # 1. 创建txt文件并写入文本内容 text = "life was like a box of chocolates, you never know what you‘re going to get." with open("text.txt", "w") as file: file.write(text) # 2. 统计单词频率 word_frequency = {} translator = str.maketrans('', '', string.punctuation) words = text.translate(translator).lower().split() # 去除标点符号并转为小写,然后按空格分割单词 for word in words: if word not in word_frequency: word_frequency[word] = 1 else: word_frequency[word] += 1 # 3. 对键进行排序并输出 sorted_keys = sorted(word_frequency.keys()) for key in sorted_keys: print("{:<10} {}".format(key, word_frequency[key])) ``` 运行上述代码后,将会创建一个名为text.txt的txt文件,并写入指定的文本内容。然后程序会统计文本中单词的频率,并按字母a-z的顺序对单词进行排序后输出。输出的格式为单词(左对齐,宽度为10个字符)和对应的频率。 [2024-05-30 10:30:24 | AI写代码神器 | 697点数解答]

相关提问