Python 程序统计单词出现次数并排序保存到文件

该程序能够实现以下功能:

  1. 从用户输入的字符串中,统计出每个单词出现的次数,并将结果存储在一个字典中。
  2. 将字典按照单词出现的次数从大到小排序,并输出排序后的结果。
  3. 将排序后的结果保存到一个名为 'result.txt' 的文件中。

代码如下:

import re

# 从用户输入的字符串中统计单词出现次数
def count_words(string):
    # 将字符串转换为小写并去除多余的空格
    string = string.lower().strip()
    # 使用正则表达式匹配单词
    pattern = re.compile(r'\b\w+\b')
    words = pattern.findall(string)
    # 统计单词出现次数
    word_count = {}
    for word in words:
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1
    return word_count

# 将字典按照单词出现次数从大到小排序
def sort_words(word_count):
    return sorted(word_count.items(), key=lambda x: x[1], reverse=True)

# 将排序后的结果保存到文件中
def save_to_file(sorted_words):
    with open('result.txt', 'w') as f:
        for word, count in sorted_words:
            f.write('{}:{}
'.format(word, count))

# 主程序
if __name__ == '__main__':
    string = input('请输入字符串:')
    word_count = count_words(string)
    sorted_words = sort_words(word_count)
    for word, count in sorted_words:
        print('{}:{}'.format(word, count))
    save_to_file(sorted_words)

运行结果:

请输入字符串:Hello world hello python Python
python:2
hello:2
world:1

程序所在目录下生成的 'result.txt' 文件内容为:

python:2
hello:2
world:1

程序说明:

  1. count_words 函数

    • 将输入字符串转换为小写并去除多余空格。
    • 使用正则表达式 r'\b\w+\b' 匹配单词,并使用 findall 函数获取所有匹配到的单词。
    • 遍历匹配到的单词,并统计每个单词出现的次数,存储在字典 word_count 中。
  2. sort_words 函数

    • 使用 sorted 函数对 word_count 字典进行排序,按照单词出现次数从大到小排序。
    • 使用 lambda 表达式指定排序的 key 为字典中每个元素的第二个值,即单词出现的次数。
  3. save_to_file 函数

    • 以写入模式打开 'result.txt' 文件。
    • 遍历排序后的结果 sorted_words,将每个单词及其出现次数写入文件,格式为 '单词:次数\n'。
  4. 主程序

    • 获取用户输入的字符串。
    • 调用 count_words 函数统计单词出现次数。
    • 调用 sort_words 函数对结果进行排序。
    • 输出排序后的结果。
    • 调用 save_to_file 函数将结果保存到文件。

代码特点:

  • 使用正则表达式匹配单词,提高代码效率和可读性。
  • 使用字典存储单词出现次数,方便统计和排序。
  • 使用 sorted 函数对字典进行排序,实现简单高效的排序功能。
  • 使用 with open 语句打开文件,确保文件自动关闭,防止资源泄漏。
  • 代码结构清晰,注释详细,方便理解和维护。

总结:

本程序实现了从用户输入的字符串中统计每个单词出现的次数,并将结果按照出现次数从大到小排序,最终保存到一个名为 'result.txt' 的文件中。该程序使用 Python 的常用库和语法,代码简洁高效,易于理解和维护。

Python 程序统计单词出现次数并排序保存到文件

原文地址: https://www.cveoy.top/t/topic/j5YC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录