代码生成(使用Python编写一个程序,输入一个文件和一个字符串,统计该字符在文件中出现的次数。)
时间: 2024-02-27 19:57:41 浏览: 88
好的,这是一个简单的 Python 代码示例,可以实现你所需的功能:
```python
def count_occurrences(file_path, target_string):
count = 0
with open(file_path, 'r') as file:
for line in file:
count += line.count(target_string)
return count
```
你可以将文件路径和目标字符串作为参数传递到函数中,并返回目标字符串在文件中出现的次数。例如,如果你想要统计文件 "example.txt" 中字符串 "Hello" 的出现次数,可以这样调用函数:
```python
count = count_occurrences("example.txt", "Hello")
print("The string 'Hello' appears", count, "times in the file.")
```
希望这可以帮助你!
阅读全文