如何读取文档中单词出现的次数,并按照出行次数多少从大到小输出 的代码
时间: 2024-05-09 07:16:54 浏览: 7
以下是Python代码示例:
```
# 打开文件并读取内容
with open('example.txt', 'r') as file:
text = file.read()
# 将文本转换为小写并分词
words = text.lower().split()
# 统计单词出现次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 按照出现次数多少,从大到小排序单词列表
sorted_words = sorted(word_count, key=word_count.get, reverse=True)
# 输出单词及其出现次数
for word in sorted_words:
print(word, word_count[word])
```
该代码首先打开文件并将内容读入到变量`text`中。然后将文本转换为小写并使用空格分词,将结果存储在列表`words`中。接着统计每个单词出现的次数,并将结果存储在字典`word_count`中。最后,将单词列表按照出现次数从大到小排序,然后遍历输出每个单词及其出现的次数。
相关问题
编写java程序统计一篇英语文档中个单词出现的次数,并按单词出现频率由高到低进行输出;
以下是一个简单的 Java 程序,可以实现统计一篇英语文档中单词出现次数并按频率排序的功能:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class WordCount {
public static void main(String[] args) throws FileNotFoundException {
// 读取文件
Scanner scanner = new Scanner(new File("input.txt"));
// 统计每个单词出现的次数
Map<String, Integer> wordCountMap = new HashMap<>();
while (scanner.hasNext()) {
String word = scanner.next().toLowerCase();
if (wordCountMap.containsKey(word)) {
wordCountMap.put(word, wordCountMap.get(word) + 1);
} else {
wordCountMap.put(word, 1);
}
}
// 将结果按照出现次数排序
List<Map.Entry<String, Integer>> sortedWordCountList = new ArrayList<>(wordCountMap.entrySet());
sortedWordCountList.sort((o1, o2) -> o2.getValue() - o1.getValue());
// 输出结果
for (Map.Entry<String, Integer> entry : sortedWordCountList) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
其中,`input.txt` 是输入文件的文件名,程序通过 `Scanner` 读取输入文件中的单词,并使用 `HashMap` 统计每个单词出现的次数。然后,将统计结果按照出现次数排序,并输出结果。需要注意的是,为了统计的准确性,程序在读取每个单词时将其转换成小写字母。
利用nltk统计文档中各单词出现的次数
以下是一个使用nltk统计文档中各单词出现次数的示例代码:
```python
import nltk
from nltk.tokenize import word_tokenize
from collections import Counter
# 读取文本文件
with open('example.txt', 'r') as file:
text = file.read()
# 分词
words = word_tokenize(text)
# 统计单词出现次数
word_counts = Counter(words)
# 输出前10个出现次数最多的单词
for word, count in word_counts.most_common(10):
print(word, count)
```
在代码中,首先使用 `open()` 函数读取文本文件,然后使用 `word_tokenize()` 函数将文本分词为单词列表。接着,使用 `Counter()` 函数统计每个单词出现的次数,并将结果存储在 `word_counts` 变量中。最后,使用 `most_common()` 方法输出出现次数最多的前10个单词及其出现次数。