我不想import Counter
时间: 2023-07-21 15:32:29 浏览: 44
好的,你可以使用普通的字典来统计单词出现次数。以下是代码实现:
```python
s = "This is a test string. This string is for testing purposes. Test is the keyword in this string."
words = s.lower().split() # 将字符串转为小写,并按空格分割为单词列表
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
top_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:10] # 获取出现次数最多的前 10 个单词
with open('wordnum.txt', 'w') as f:
for word, count in top_words:
f.write(f"{word}: {count}\n")
```
这里我们使用一个字典 word_count 来存储单词出现次数,遍历单词列表,如果单词已经在字典中,将其出现次数加 1,否则将其添加到字典中,并将其出现次数初始化为 1。然后使用 sorted 函数对字典进行排序,获取出现次数最多的前 10 个单词。最后,使用文件操作将单词和出现次数写入 wordnum.txt 文件中。
这种方法虽然没有使用 Counter 模块方便,但是也可以实现单词统计的功能。希望对你有所帮助!