帮我写一段Python代码,用来统计某串字符在电脑中的某个文件夹中的每个文件中出现的次数
时间: 2024-05-04 11:15:19 浏览: 122
以下是一段Python代码,用来统计某串字符在电脑中的某个文件夹中的每个文件中出现的次数:
```python
import os
def count_occurrences(folder_path, substring):
file_occurrences = {}
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path):
with open(file_path, 'r') as file:
file_content = file.read()
occurrences = file_content.count(substring)
file_occurrences[filename] = occurrences
return file_occurrences
```
使用方法:
```python
folder_path = '/path/to/folder'
substring = 'example'
occurrences = count_occurrences(folder_path, substring)
print(occurrences)
```
将`/path/to/folder`替换成要统计的文件夹路径,将`example`替换成要统计的字符串。该代码将返回一个字典,其中包含每个文件名和该文件中目标字符串出现的次数。
阅读全文