统计文本中出现的数量最高的前5个单词

def read_file():
with open(‘C:/Users/84785/PycharmProjects/pythonProject/3.txt’, ‘r’, encoding=‘utf-8’) as f:
word = [] # 空列表用来存储文本中的单词
# readlins为分行读取文本,且返回的是一个列表,每行的数据作为列表中的一个元素:
for word_str in f.readlines():
# 去除原文中的逗号 双引号
word_str = word_str.replace(’,’, ‘’).replace(’"’, ‘’)
# strip去除每行字符串数据两边的空白字符
word_str = word_str.strip()
# 对单行字符串通过空格进行分割,返回一个列表
word_list = word_str.split(’ ')
# 将分割后的列表内容,添加到word空列表中
word.extend(word_list)
# 定义一个新字典存放单词以及数量
dic = {}
# 循环列表中的单词统计数量
for i in word:
count = word.count(i)
# 把数量设为字典的value值
dic[i] = count
# 使用sorted()方法对其排序sorted(iterable, key=None, reverse=False) iterable为可迭代的对象,使用items(
# )方法以列表返回可遍历的(键,值)元组数据,key为比较的元素
dic1 = sorted(dic.items(), key=lambda d: d[1], reverse=True)
print(dic1)
for i in range(5):
print(dic1[i])

read_file()
在这里插入图片描述
在这里插入图片描述

### 实现 Trie 树以统计文本中最常出现的十个单词 为了高效地处理符串匹配和检索操作,Trie 树是一种非常适合的数据结构。通过构建 Trie 树记录每个节点经过次数,可以方便地计算词频。 #### 构建 Trie 节点类 首先定义一个 `TrieNode` 类来表示 Trie 的各个节点: ```cpp struct TrieNode { bool isEnd; int frequency; // 记录该单词出现次数 unordered_map<char, TrieNode*> children; TrieNode() : isEnd(false), frequency(0) {} }; ``` #### 定义 Trie 树类及其方法 接着创建 `TrieTree` 类用于管理整个典树的操作: ```cpp class TrieTree { private: TrieNode* root; public: TrieTree() { root = new TrieNode(); } ~TrieTree(); void insert(const string& word); vector<pair<string, int>> getTopKFrequentWords(int k); }; // 插入新单词到 Trie 中 void TrieTree::insert(const string& word) { TrieNode* node = root; for (char ch : word) { if (!node->children[ch]) { node->children[ch] = new TrieNode(); } node = node->children[ch]; } ++node->frequency; } // 使用析构函数释放内存资源 TrieTree::~TrieTree() { queue<TrieNode*> q; q.push(root); while(!q.empty()) { auto curr = q.front(); q.pop(); for(auto it=curr->children.begin();it!=curr->children.end();++it){ q.push(it->second); } delete curr; } } ``` #### 获取最频繁使用的 K 个单词 最后编写获取指定数量最高频率单词的方法: ```cpp vector<pair<string, int>> TrieTree::getTopKFrequentWords(int k) { priority_queue<pair<int, string>, vector<pair<int, string>>, greater<>> minHeap; function<void(TrieNode*, string)> dfs = [&](TrieNode* node, string prefix) -> void { if (minHeap.size() >= static_cast<size_t>(k)) { if (node->isEnd && node->frequency > minHeap.top().first) { minHeap.pop(); minHeap.emplace(node->frequency, prefix); } else if (node->isEnd) { minHeap.emplace(node->frequency, prefix); } } else if (node->isEnd) { minHeap.emplace(node->frequency, prefix); } for (auto&& p : node->children) { dfs(p.second, prefix + p.first); } }; dfs(root, ""); vector<pair<string, int>> result(minHeap.size()); size_t i = 0; while (!minHeap.empty()) { result[i++] = make_pair(minHeap.top().second, minHeap.top().first); minHeap.pop(); } reverse(result.begin(), result.end()); return result; } ``` 上述代码实现了基本功能,但在实际应用中可能还需要考虑更多细节优化性能以及边界情况处理[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值