我想计算路径/test/中文件列表(.txt)中的笑脸列表。在
下面是我在所有文件中统计笑脸的方法。在
def count_string_occurrence():
import os
total = 0
x = 0
for file in os.listdir("C:/users/M/Desktop/test"):
if file.endswith(".txt"):
string = ":)" #define search term
f=open(file,encoding="utf8")
contents = f.read()
f.close()
x=contents.count(string)
total +=int(x) #calculate occurance of smiley in all files
print("Number of " + string + " in all files equals " + str(total))
count_string_occurrence()
我现在如何循环不同的笑脸并分别打印每个笑脸的结果?因为我已经循环了不同的文件,所以变得复杂了。在
您可以将搜索字符串设为函数参数,然后使用不同的搜索项多次调用函数。在
另一种方法是将smilies列表传递给函数,然后在
if
块内进行迭代。可以将结果存储在dict中,格式为{ ':)': 5, ':P': 4, ... }
关于您的问题:您可以保存一个字典,其中包含每个字符串的计数并返回该值。但如果你保持你目前的结构,那就不好了。在
我的建议是:
glob
的作业。在defaultdict
,这样就不必关心计数最初是不是0
。在修改代码:
glob
调用改为for file_name in glob.iglob('**/*.txt', recursive=True)
,这样它将递归地搜索,以备需要。在这将打印如下内容:
defaultdict(<class 'int'>, {':P': 2, ':)': 1, '=]': 1})
相关问题 更多 >
编程相关推荐