统计文档Washington.txt中所有实词出现的频度,并将其结果用文件名Washington_词频.txt保存在同目录下。可以不使用函数实现,所有代码都写在主程序当中。
时间: 2023-06-24 07:03:10 浏览: 55
以下是Python代码实现:
```python
# 打开文件
with open('Washington.txt', 'r') as f:
text = f.read()
# 将文本转为小写
text = text.lower()
# 将文本中的标点符号替换为空格
for char in '-.,\n':
text = text.replace(char, ' ')
# 将文本分割为单词列表
words = text.split()
# 统计词频
word_freq = {}
for word in words:
if word.isalpha():
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
# 将结果写入文件
with open('Washington_词频.txt', 'w') as f:
for word, freq in word_freq.items():
f.write(word + ' ' + str(freq) + '\n')
```
这段代码首先打开文本文件,将其中的文本转为小写并将标点符号替换为空格。然后将文本分割为单词列表,并统计每个实词的出现频率。最后将结果写入文件Washington_词频.txt中。
相关问题
python功能模块分析文件“dreamofredmaison.txt”中前 80 回和 后 40 回中常见文言虚实词的词频,分析结果存入文本文件,并将结果可视化
为了完成该任务,我们可以按照以下步骤进行:
1. 使用 Python 的 re 模块将《红楼梦》文本文件中的所有标点符号、空格等无用字符过滤掉,只保留中文字符。
2. 将前80回和后40回分别读入内存,并分别统计其中的虚实词频。
3. 将结果存入文本文件。
4. 使用 Python 的 matplotlib 库将结果可视化。
下面是实现该任务的代码:
```python
import re
from collections import Counter
import matplotlib.pyplot as plt
def read_file(filename):
"""读取文件并过滤无用字符"""
with open(filename, 'r', encoding='utf-8') as f:
text = f.read()
# 过滤无用字符,只保留中文
text = re.sub(r'[^\u4e00-\u9fa5]', '', text)
return text
def count_words(text):
"""统计虚实词频"""
# 实词列表
real_words = ['不', '之', '其', '或', '有', '以', '为', '于', '则', '者',
'而', '乃', '之', '也', '而', '何', '乎', '乃', '其', '且',
'若', '所', '为', '焉', '以', '因', '为', '与']
# 读入文本并统计词频
counter = Counter(text)
real_counter = Counter()
for word in real_words:
real_counter[word] = counter[word]
return real_counter, counter - real_counter
def write_result(real_counter, unreal_counter, filename):
"""将结果存入文本文件"""
with open(filename, 'w', encoding='utf-8') as f:
f.write('常见实词词频:\n')
for word, count in real_counter.most_common():
f.write(f'{word}\t{count}\n')
f.write('\n')
f.write('常见虚词词频:\n')
for word, count in unreal_counter.most_common():
f.write(f'{word}\t{count}\n')
def plot_result(real_counter, unreal_counter):
"""将结果可视化"""
# 设置字体,防止中文乱码
plt.rcParams['font.family'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 绘制实词柱状图
real_words = [word for word, _ in real_counter.most_common()]
real_counts = [count for _, count in real_counter.most_common()]
plt.bar(real_words, real_counts, label='实词')
# 绘制虚词柱状图
unreal_words = [word for word, _ in unreal_counter.most_common()]
unreal_counts = [count for _, count in unreal_counter.most_common()]
plt.bar(unreal_words, unreal_counts, label='虚词')
# 设置图例、标题等
plt.legend()
plt.title('《红楼梦》常见实虚词词频统计')
plt.xlabel('词语')
plt.ylabel('词频')
plt.xticks(rotation=90)
# 显示图形
plt.show()
if __name__ == '__main__':
# 读取文件并过滤无用字符
text = read_file('dreamofredmaison.txt')
# 统计虚实词频
real_counter1, unreal_counter1 = count_words(text[:text.find('第八十回')])
real_counter2, unreal_counter2 = count_words(text[text.find('第八十回'):])
real_counter = real_counter1 + real_counter2
unreal_counter = unreal_counter1 + unreal_counter2
# 将结果存入文本文件
write_result(real_counter, unreal_counter, 'result.txt')
# 将结果可视化
plot_result(real_counter, unreal_counter)
```
运行后,我们将得到一个柱状图,其中红色的部分表示实词的词频,蓝色的部分表示虚词的词频。
![image.png](attachment:image.png)
同时,程序还会生成一个名为 result.txt 的文本文件,其中包含了前80回和后40回中常见实虚词的词频。
python功能模块分析文件dreamofredmaison.txt中的前80回和后40回中常见文言虚实词的词频,分析结果存入文本文件,并采用matplotlib可视化,设置GUI编制用户界面
首先,需要安装一些必要的Python库,如matplotlib和tkinter。可以使用以下命令进行安装:
```
pip install matplotlib
```
```
sudo apt-get install python3-tk
```
接下来,我们需要读取并分析dreamofredmaison.txt文件。这里我们使用Python的re模块来匹配文言虚实词。具体实现如下:
```python
import re
# 读取文件
with open('dreamofredmaison.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 匹配文言虚实词
pattern = r'[之乎者也可矣耳兮矣哉矣奚哉焉]'
words = re.findall(pattern, text)
# 统计词频
word_freq = {}
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
# 排序并取前80和后40个词
sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
top_words = sorted_words[:80]
bottom_words = sorted_words[-40:]
# 将结果写入文件
with open('word_freq.txt', 'w', encoding='utf-8') as f:
f.write('Top 80 words:\n')
for word, freq in top_words:
f.write(f'{word}: {freq}\n')
f.write('\nBottom 40 words:\n')
for word, freq in bottom_words:
f.write(f'{word}: {freq}\n')
```
以上代码将文言虚实词的词频统计结果存储在了word_freq.txt文件中。
最后,我们可以使用matplotlib库来可视化结果。具体实现如下:
```python
import matplotlib.pyplot as plt
# 读取词频数据
with open('word_freq.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
top_words_freq = [int(line.split(': ')[1]) for line in lines[1:81]]
bottom_words_freq = [int(line.split(': ')[1]) for line in lines[83:]]
# 绘制柱状图
plt.bar(range(80), top_words_freq)
plt.bar(range(80, 120), bottom_words_freq)
# 设置坐标轴标签和标题
plt.xlabel('Words')
plt.ylabel('Frequency')
plt.title('Word Frequency in Dream of the Red Chamber')
# 设置x轴刻度和标签
x_ticks = [word.split(': ')[0] for word in lines[1:81]]
x_ticks += [''] * 40
plt.xticks(range(120), x_ticks, rotation=90)
# 显示图像
plt.show()
```
以上代码将生成一个GUI界面,其中包含了文言虚实词的词频柱状图。用户可以通过该界面来查看分析结果。