searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

平时经常会使用到的Python 脚本(4)

2024-11-22 17:34:56
2
0

1. 统计文本文件中的单词频率脚本功能

统计文本文件中每个单词出现的次数。

from collections import Counter
import re

# 统计单词频率
with open('example.txt', 'r', encoding='utf-8') as file:
    text = file.read().lower()  # 转为小写以避免重复
    words = re.findall(r'\w+', text)  # 提取单词
    word_count = Counter(words)
    print(word_count)

适合文本分析和信息检索,如博客文章或书籍的关键词分析。

2. 数据可视化

使用 Matplotlib 库绘制数据图形。

import matplotlib.pyplot as plt

# 数据准备
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# 绘制图形
plt.plot(x, y, marker='o')
plt.title('Simple Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid()
plt.show()

适合用于分析结果展示,比如展示销售趋势或实验数据。

0条评论
0 / 1000
王****际
180文章数
2粉丝数
王****际
180 文章 | 2 粉丝
原创

平时经常会使用到的Python 脚本(4)

2024-11-22 17:34:56
2
0

1. 统计文本文件中的单词频率脚本功能

统计文本文件中每个单词出现的次数。

from collections import Counter
import re

# 统计单词频率
with open('example.txt', 'r', encoding='utf-8') as file:
    text = file.read().lower()  # 转为小写以避免重复
    words = re.findall(r'\w+', text)  # 提取单词
    word_count = Counter(words)
    print(word_count)

适合文本分析和信息检索,如博客文章或书籍的关键词分析。

2. 数据可视化

使用 Matplotlib 库绘制数据图形。

import matplotlib.pyplot as plt

# 数据准备
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# 绘制图形
plt.plot(x, y, marker='o')
plt.title('Simple Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid()
plt.show()

适合用于分析结果展示,比如展示销售趋势或实验数据。

文章来自个人专栏
文章 | 订阅
0条评论
0 / 1000
请输入你的评论
0
0