python代码实现根据用户需求(用户输入感兴趣的词),统计并输出词频,且打印该词出现在哪一句的什么位置
时间: 2024-06-10 19:06:21 浏览: 6
好的,这是一个很好的问题!以下是Python代码实现:
```python
import re
def count_word_frequency(user_input):
# 读取文本文件
with open('document.txt', 'r') as file:
data = file.read()
# 标点符号、数字等替换为空格
data = re.sub(r'[^\w\s]', '', data)
# 将文本转换为小写
data = data.lower()
# 分割句子
sentences = data.split('.')
# 初始化计数器
word_count = {}
# 遍历每个句子
for idx, sentence in enumerate(sentences):
# 分割单词
words = sentence.split()
# 遍历每个单词
for word in words:
# 判断单词是否为用户输入的词
if word == user_input.lower():
# 将词频计数器加一
if idx not in word_count:
word_count[idx] = []
word_count[idx].append(words.index(word) + 1)
return word_count
if __name__ == '__main__':
user_input = input('请输入你感兴趣的词:')
word_count = count_word_frequency(user_input)
# 打印词频以及出现位置
print(f'词频:{len(word_count)}')
for key in word_count:
print(f'出现在第{key+1}句,位置分别为{word_count[key]}')
```
该代码实现了根据用户输入的词,统计词频,并打印出每个出现位置对应的句子和位置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)