Python 统计文件中字符串出现次数
可以使用 Python 中的 count() 方法来统计文件中某个字符串出现的次数。
以下是一个示例代码:
filename = 'example.txt'
search_string = 'hello'
with open(filename, 'r') as file:
contents = file.read()
count = contents.count(search_string)
print(f'The string '{search_string}' appears {count} times in the file.')
在上述代码中,首先指定要搜索的文件名和要查找的字符串。然后使用open()函数打开文件,并使用read()方法读取文件内容。接下来,使用count()方法统计字符串出现的次数,并将结果存储在变量count中。最后,输出结果。
请注意,上述代码假定文件中的文本是 ASCII 编码。如果文件使用其他编码,请在打开文件时指定相应的编码。例如:
with open(filename, 'r', encoding='utf-8') as file:
# ...
原文地址: https://www.cveoy.top/t/topic/jXmT 著作权归作者所有。请勿转载和采集!