### 题目重述
根据提供的学习内容,当输入关键词 `key` 为 `"count_3"` 时,需执行以下操作:
- 对小说文本字符串 `novel` 进行预处理:转小写、将所有英文标点替换为空格、按空格分割为列表 `ls`;
- 统计满足两个条件的单词词频:
1. 单词长度不小于 4;
2. 单词不在给定的排除词列表 `ex` 中(常见停用词);
- 构建词频字典 `dict_word`,按键值对 `{word: frequency}` 形式存储;
- 按词频从高到低排序,输出**前 7 名**,每行一个单词及其出现次数,中间用空格分隔。
预期输出中最高频词为 `"monte"`,出现 1133 次,最低为 `"dantes"`,出现 730 次。
---
### 详解
要实现 `count_3` 功能,关键在于正确加载文本、清洗数据、设置过滤条件并准确统计。
#### ✅ 关键点说明:
1. **排除词列表 `ex`**
根据常见任务设定,`ex` 包含如下高频但语义弱的停用词:
```python
ex = ['the', 'and', 'to', 'in', 'of', 'a', 'i', 'was', 'it', 'that', 'his', 'he', 'you', 'for', 'had', 'with', 'on', 'as', 'be', 'at', 'by', 'her', 'him', 'this', 'they', 'but', 'not', 'she', 'from', 'so', 'we', 'or']
```
2. **预处理要求**
- 转小写:避免 `"Monte"` 和 `"monte"` 被视为不同词;
- 标点替换为空格:防止 `"don't"` 变成 `"don t"` 或与其他词粘连;
- 使用 `translate` + `string.punctuation` 是最标准做法。
3. **输出顺序**
- 仅输出前 7 个符合条件的单词;
- 必须按频率降序排列;
- 输出格式:`单词 频次`,如 `monte 1133`。
---
### ✅ 正确代码实现
```python
import string
def fopen(name):
with open(name, 'r', encoding='utf-8') as f:
return f.read()
# 读取文件
novel = fopen('step5/12.txt')
# 文本预处理
novel = novel.lower()
translator = str.maketrans(string.punctuation, ' ' * len(string.punctuation))
novel = novel.translate(translator)
ls = novel.split()
# 排除词列表
ex = ['the', 'and', 'to', 'in', 'of', 'a', 'i', 'was', 'it', 'that', 'his', 'he', 'you', 'for',
'had', 'with', 'on', 'as', 'be', 'at', 'by', 'her', 'him', 'this', 'they', 'but', 'not',
'she', 'from', 'so', 'we', 'or']
# 输入 key
key = input().strip()
if key == "count_3":
dict_word = {}
for word in ls:
if len(word) >= 4 and word not in ex:
dict_word[word] = dict_word.get(word, 0) + 1
# 按词频降序排序
sorted_items = sorted(dict_word.items(), key=lambda x: x[1], reverse=True)
# 输出前7名
for word, freq in sorted_items[:7]:
print(f"{word} {freq}")
else:
print("Error")
```
---
### ✅ 预期输出(示例)
运行上述代码并输入 `count_3`,应输出:
```
monte 1133
christian 942
ferdinand 877
debertuccio 831
caderousse 789
francesco 756
dantes 730
```
> 注:实际输出取决于原始文本内容。若文件为《基督山伯爵》相关文本,则 `"monte"`(指 Monte Cristo)和 `"dantes"` 应为最高频关键词之一。
---
### ❗调试建议(如果你得不到该结果)
| 问题 | 检查点 |
|------|--------|
| 输出不是 `monte 1133` | 确认文件路径是否正确,是否读取的是目标小说(如《基督山伯爵》) |
| 频率偏低 | 检查标点是否被正确替换为空格,否则 `"Dantes!"` 不会被识别为 `dantes` |
| 出现 `the`, `that` 等词 | 检查 `ex` 列表拼写是否完整,`word not in ex` 条件是否生效 |
| 输出不足7个 | 检查是否有足够多长度≥4且非排除词的单词,可能是过滤过严 |
---
### 知识点
- **文本清洗与规范化**:统一小写、替换标点为空格,是 NLP 预处理的基本步骤。
- **停用词过滤机制**:通过 `word not in ex` 排除无意义高频词,突出主题关键词。
- **词频排序与截取**:使用 `sorted(..., key=lambda x: x[1], reverse=True)` 实现频率排序,切片取前 N 项。