英文词频统计python代码
时间: 2023-07-02 08:06:46 浏览: 45
以下是一个简单的 Python 代码示例,用于对给定文本中的单词进行词频统计:
```python
text = "This is a sample text with several words. We will count the frequency of each word in this text."
# 将文本转换为小写,以便于统计
text = text.lower()
# 用空格将文本分割成单词列表
words = text.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(word, count)
```
输出结果:
```
this 1
is 1
a 1
sample 1
text 2
with 1
several 1
words. 1
we 1
will 1
count 1
the 2
frequency 1
of 1
each 1
word 1
in 1
```
这个代码示例比较简单,如果你要进行更复杂的文本处理,可能需要使用更高级的 Python 库,如 NLTK 或 SpaCy。
相关问题
Hamlet英文词频统计 python代码
以下是一个简单的Python程序,用于读取Hamlet英文文本文件并统计单词出现的频率:
```python
from collections import Counter
# 读取文件
with open('hamlet.txt', 'r') as f:
text = f.read()
# 将文本转换为小写,并按照空格分割单词
words = text.lower().split()
# 统计单词出现的频率
word_count = Counter(words)
# 打印前10个出现频率最高的单词及其出现次数
for word, count in word_count.most_common(10):
print(word, count)
```
注意:在运行此程序之前,需要将Hamlet文本文件保存为hamlet.txt,并将其放在与程序相同的目录下。
Harry Potter 英文词频统计python代码
以下是一个简单的 Python 代码,用于统计《哈利波特》(Harry Potter)第一部小说中单词的出现频率。需要注意的是,这个代码只是一个基础的示例,可能需要根据具体情况进行修改和优化。
```python
# 导入所需的库
import string
# 打开文件并读取文本
with open('harry_potter.txt', 'r') as f:
text = f.read()
# 去除标点符号并转化成小写
text = text.translate(str.maketrans('', '', string.punctuation)).lower()
# 将文本拆分为单词
words = text.split()
# 创建一个字典来存储单词频率
word_freq = {}
# 统计单词频率
for word in words:
if word not in word_freq:
word_freq[word] = 1
else:
word_freq[word] += 1
# 打印最常见的单词
for word, freq in sorted(word_freq.items(), key=lambda x: x[1], reverse=True):
print(f'{word}: {freq}')
```
这个代码使用了 Python 的内置函数和库,包括:
- `open` 函数用于打开文件;
- `string` 模块中的 `punctuation` 常量用于获取标点符号;
- `translate` 方法用于去除文本中的标点符号;
- `lower` 方法用于将文本转化为小写;
- `split` 方法用于将文本拆分为单词;
- 字典用于存储每个单词出现的次数;
- `sorted` 函数用于按照单词频率排序并打印结果。