You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
1.2 KiB
34 lines
1.2 KiB
本文旨在通过一个案例(读取 data 目录下 100 篇小说文本,统计词频并输出前 10 高频词)来说明如何提升代码工程质量。
|
|
教案将逐步展示不同编程技术的应用,并分析其对代码可读性、可维护性、可扩展性和复用性的提升。
|
|
|
|
本案例不做性能提升方面的考量。
|
|
|
|
|
|
## 起点:基础实现
|
|
|
|
```
|
|
import os
|
|
|
|
files = os.listdir('data')
|
|
word_count = {}
|
|
for file in files:
|
|
with open('data/' + file, 'r', encoding='utf-8') as f:
|
|
text = f.read()
|
|
words = text.split() # 假设简单按空格分词
|
|
for word in words:
|
|
if word in word_count:
|
|
word_count[word] += 1
|
|
else:
|
|
word_count[word] = 1
|
|
|
|
# 排序并输出前10
|
|
sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
|
|
for i in range(10):
|
|
print(sorted_words[i])
|
|
```
|
|
|
|
## 问题分析
|
|
- 可读性差:没有清晰的功能划分,代码逻辑混杂,难以阅读理解维护。
|
|
- 扩展性差:如果需要更改分词逻辑、文件路径或输出格式,需修改多处代码。
|
|
- 容错性差:未处理文件读取失败、空文件等问题。
|
|
- 复用性低:逻辑无法直接复用在其他类似任务中。 |