统计一篇文章中每个单词出现的次数
时间: 2023-09-03 08:12:54 浏览: 113
可以使用Python来实现。
以下是实现思路:
1. 读取文章,把文章的内容存储在一个字符串中
2. 把字符串分割成单词列表,可以使用split()函数
3. 定义一个字典,用于存储每个单词出现的次数
4. 对于每个单词,如果它已经存在于字典中,就把它的计数器加1,否则就把它添加到字典中,并且计数器初始化为1
5. 最后遍历字典,输出每个单词出现的次数
以下是Python代码实现:
```
# 读取文章
with open('article.txt', 'r') as f:
content = f.read()
# 把字符串分割成单词列表
words = content.split()
# 定义一个字典,用于存储每个单词出现的次数
word_counts = {}
# 统计每个单词出现的次数
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# 输出每个单词出现的次数
for word, count in word_counts.items():
print(word, count)
```
其中,`article.txt`是文章的文件名,需要根据实际情况修改。
相关问题
用c语言统计一篇文章中每个单词出现的次数
以下是用C语言实现统计文章中每个单词出现次数的示例代码:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD_LENGTH 50
#define MAX_WORDS 1000
int main() {
char article[10000];
printf("请输入文章:\n");
fgets(article, 10000, stdin);
char words[MAX_WORDS][MAX_WORD_LENGTH];
int freq[MAX_WORDS] = {0};
int num_words = 0;
char *p_word = strtok(article, " ,.\n");
while (p_word != NULL && num_words < MAX_WORDS) {
strncpy(words[num_words], p_word, MAX_WORD_LENGTH);
words[num_words][MAX_WORD_LENGTH - 1] = '\0';
for (int i = 0; i < strlen(words[num_words]); i++) {
words[num_words][i] = tolower(words[num_words][i]);
}
freq[num_words]++;
num_words++;
p_word = strtok(NULL, " ,.\n");
while (p_word != NULL && strlen(p_word) == 1 && ispunct(p_word[0])) {
p_word = strtok(NULL, " ,.\n");
}
for (int i = 0; i < num_words - 1; i++) {
if (strcmp(words[i], words[num_words - 1]) == 0) {
freq[i]++;
num_words--;
}
}
}
printf("单词\t\t出现次数\n");
printf("=========================\n");
for (int i = 0; i < num_words; i++) {
printf("%-20s%d\n", words[i], freq[i]);
}
return 0;
}
```
该程序首先读入文章,然后将文章分解为单词。对于每个单词,程序将其转换为小写字母,并在单词列表中查找是否已经出现过。如果出现过,那么该单词的出现次数加1,否则将该单词添加到单词列表中。最后,程序输出每个单词及其出现次数。
给定任意一篇文章,统计其中单词出现数量
好的,我可以帮您实现这个功能。首先,我们需要将文章分解成单词,可以使用 Python 中的 `split()` 函数。然后,我们可以使用字典来存储每个单词和它出现的次数。
下面是一个示例代码:
```python
article = "This is a sample article for word count. We will count the number of times each word appears in this article."
# 将文章分解成单词
words = article.split()
# 定义一个字典来存储单词和它出现的次数
word_count = {}
# 统计单词出现的次数
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
# 输出每个单词和它出现的次数
for word, count in word_count.items():
print(f"{word}: {count}")
```
输出结果如下:
```
This: 1
is: 1
a: 1
sample: 1
article: 2
for: 1
word: 2
count.: 1
We: 1
will: 1
the: 1
number: 1
of: 1
times: 1
each: 1
appears: 1
in: 1
this: 1
article.: 1
```
以上代码可以统计文章中每个单词出现的次数,并输出结果。您可以将上面的代码复制到 Python 环境中进行测试。