希幼黎 2021-05-16 12:27 采纳率: 50%
浏览 28

python问题详见内容

把词频排名前5的单词和出现频次保存到一个文本文件中,并将文件名统一格式为“姓名.txt”

  • 写回答

1条回答 默认 最新

  • 孩子快醒醒 2023-04-02 14:29
    关注
    '''假设有一段文本保存在text.txt文件中,对其进行分词后统计词频排名前5的单词和出现频次'''
    import jieba
    
    # 读取文本内容
    with open('text.txt', 'r', encoding='utf-8') as f:
        text = f.read()
    
    # 分词
    words = list(jieba.cut(text))
    
    # 统计词频
    word_freq = {}
    for word in words:
        if word in word_freq:
            word_freq[word] += 1
        else:
            word_freq[word] = 1
    
    # 排序并取前5个
    top_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:5]
    
    # 保存到文件
    filename = '姓名.txt'
    with open(filename, 'w', encoding='utf-8') as f:
        for word, freq in top_words:
            f.write(f'{word}\t{freq}\n')
    
    
    评论

报告相同问题?