擅长:python、mysql、java
<p>您可以将搜索字符串设为函数参数,然后使用不同的搜索项多次调用函数。在</p>
<pre><code>def count_string_occurrence(string):
import os
total = 0
x = 0
for file in os.listdir("C:/users/M/Desktop/test"):
if file.endswith(".txt"):
f=open(file,encoding="utf8")
contents = f.read()
f.close()
x=contents.count(string)
total +=int(x) #calculate occurance of smiley in all files
return total
smilies = [':)', ':P', '=]']
for s in smilies =
total = count_string_occurrence(s)
print("Number of {} in all files equals {}".format( s, total ))
</code></pre>
<p>另一种方法是将smilies列表传递给函数,然后在<code>if</code>块内进行迭代。可以将结果存储在dict中,格式为<code>{ ':)': 5, ':P': 4, ... }</code></p>