python统计text文件file1和file2 中attention出现次数
时间: 2024-03-24 21:37:23 浏览: 15
您可以使用Python中的字典(Dictionary)来实现这个功能。以下是一个示例代码:
```python
# 打开文件并读取内容
with open("file1.txt", "r") as f1:
text1 = f1.read()
with open("file2.txt", "r") as f2:
text2 = f2.read()
# 将文本内容转换为小写并分割成单词列表
words1 = text1.lower().split()
words2 = text2.lower().split()
# 统计单词出现的次数
counts1 = {}
counts2 = {}
for word in words1:
if word == "attention":
counts1.setdefault(word, 0)
counts1[word] += 1
for word in words2:
if word == "attention":
counts2.setdefault(word, 0)
counts2[word] += 1
# 输出结果
print("File1中attention出现了{}次".format(counts1.get("attention", 0)))
print("File2中attention出现了{}次".format(counts2.get("attention", 0)))
```
在上面的代码中,我们首先打开并读取了两个文件的内容,然后使用`lower()`方法将所有单词转换为小写,并使用`split()`方法将文本分割成单词列表。接着,我们使用一个循环遍历单词列表,统计每个单词出现的次数,并将结果存储在一个字典中。最后,我们使用`get()`方法获取字典中"attention"的出现次数,并输出结果。
相关推荐
![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)
![](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)