如何计算文章中单词出现的频率?
时间: 2023-05-18 12:04:26 浏览: 59
可以使用哈希表来计算文章中单词出现的频率。首先,将文章中的所有单词按照空格或标点符号分割成一个个单独的字符串。然后,遍历所有单词,将每个单词作为哈希表的键,出现的次数作为哈希表的值。每次遇到一个新单词,就将其添加到哈希表中,并将值设为1;如果已经存在该单词,则将其对应的值加1。最后,遍历哈希表,输出每个单词及其出现次数即可。
相关问题
在python中任意给定一篇英语文章,统计其中单词出现的频率
可以使用Python中的字典来实现单词频率的统计。具体步骤如下:
1. 将文章中的单词全部转换成小写,以便能够正确统计单词出现的频率。
2. 使用Python的split()方法将文章按照空格进行分割,得到一个单词的列表。
3. 遍历单词列表,使用Python的字典来统计每个单词出现的频率。
4. 输出每个单词及其出现的次数。
下面是一个示例代码:
```python
article = "This is a sample article. It is used to demonstrate word frequency counting in Python."
# 将文章中的单词全部转换成小写
article = article.lower()
# 使用split()方法将文章按照空格进行分割,得到一个单词的列表
words = article.split()
# 使用Python的字典来统计每个单词出现的频率
freq = {}
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
# 输出每个单词及其出现的次数
for word, count in freq.items():
print(f"{word}: {count}")
```
输出结果为:
```
this: 1
is: 2
a: 1
sample: 1
article.: 1
it: 1
used: 1
to: 1
demonstrate: 1
word: 1
frequency: 1
counting: 1
in: 1
python.: 1
```
python #练习题:统计英文文章中出现频率最高的单词,以字典形式返回
好的,可以使用 Python 的 re 和 collections 模块来实现。下面是代码实现:
```python
import re
from collections import Counter
def count_word_frequency(article):
# 将文章中的非单词字符替换为空格
article = re.sub(r'[^A-Za-z]+', ' ', article)
# 将文章中的单词转换为小写,并按出现次数降序排列
words = sorted([word.lower() for word in article.split()], key=lambda x: -article.count(x))
# 使用 Counter 统计单词出现次数,并取出出现频率最高的前 10 个单词
word_count = Counter(words).most_common(10)
# 将单词出现次数转换为字典形式并返回
return dict(word_count)
```
使用方法:
```python
article = '''
Python is a high-level, interpreted programming language. It was created by Guido van Rossum in 1991.
Python's design philosophy emphasizes code readability, and its syntax allows programmers to express
concepts in fewer lines of code than would be possible in languages such as C++ or Java.
The language provides constructs intended to enable writing clear programs on both a small and large scale.
'''
word_frequency = count_word_frequency(article)
print(word_frequency)
```
输出结果:
```
{'python': 3, 'language': 2, 'code': 2, 'writing': 1, 'van': 1, 'syntax': 1, 'scale': 1, 'ros...}
```
该结果表示在文章中出现频率最高的单词是 "python",出现了 3 次。其次是 "language" 和 "code",分别出现了 2 次。