python输出文件中单词的数量,将其中所有标点符号替换为空格,再根据空格对字符串进行切分可以得到元素为单词的列表。数字按单词统计
时间: 2024-11-27 10:24:29 浏览: 44
在Python中,你可以使用`re`模块进行正则表达式操作,先去除标点符号,然后读取文件内容,对每行文本进行处理并统计单词数量。这里是一个简单的步骤:
1. 导入必要的库:
```python
import re
```
2. 定义函数来处理文件内容:
```python
def count_words_in_file(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 使用正则表达式替换标点符号,并转换成小写
cleaned_content = re.sub(r'[^\w\s]', '', content).lower()
# 利用split()函数根据空格分割字符串,得到单词列表
words_list = cleaned_content.split()
# 统计单词频率
word_count = {word: words_list.count(word) for word in words_list}
return word_count
```
3. 调用函数并打印结果:
```python
file_path = "your_file.txt" # 替换为你需要分析的文件路径
word_counts = count_words_in_file(file_path)
for word, count in word_counts.items():
print(f"{word}: {count}")
阅读全文
相关推荐


















