Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算多个文件中的不同字符串_Python_Python 3.x - Fatal编程技术网

Python 计算多个文件中的不同字符串

Python 计算多个文件中的不同字符串,python,python-3.x,Python,Python 3.x,我想计算路径/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"):

我想计算路径/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()

现在如何循环不同的笑脸并分别打印每个笑脸的结果?因为我已经循环了不同的文件,所以它变得很复杂。

您可以将搜索字符串作为函数参数,然后使用不同的搜索词多次调用函数

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 ))

另一种方法是将smilies列表传递给函数,然后在
if
块中进行迭代。可能将结果以
{':)':5':P':4,…}

的形式存储在dict中关于您的问题:您可以保留一个包含每个字符串计数的字典并返回该值。但是如果你保持目前的结构,跟踪它就不好了

这就引出了我的建议:

  • 您将整个文件保存在内存中没有明显的原因,您可以逐行检查它并检查当前行中的字符串
  • 您还多次读取相同的文件,而您只能读取一次并检查字符串是否存在
  • 您正在检查文件的扩展名,这听起来像是
    glob
    的作业
  • 您可以使用
    defaultdict
    ,这样就不必关心计数最初是否为
    0
修改代码:

from collections import defaultdict
import glob

SMILIES = [':)', ':P', '=]']

def count_in_files(string_list):
    results = defaultdict(int)
    for file_name in glob.iglob('*.txt'):
        print(file_name)
        with open(file_name) as input_file:
            for line in input_file:
                for s in string_list:
                    if s in line:
                        results[s] += 1
    return results

print(count_in_files(SMILIES))
  • 最后,使用这种方法,如果您使用的是Python>=3.5,则可以将glob.iglob('***.txt',recursive=True)中的文件名的
    glob
    调用更改为
    ,以便在需要时递归搜索
这将打印如下内容:


defaultdict(,{:p':2',:':1',=]':1})

你所说的“循环不同的笑脸”是什么意思?你想像
:D
;)那样计算笑脸吗
:)
,等等?我的意思是我希望脚本计算大约20个笑脸的数量,并为每个笑脸输出“所有文件中X的数量等于”(X=笑脸)。笑脸包括:)、:-)、:]以及更多积极和消极笑脸的变体。谢谢,这种方法奏效了!:-)而且它确实比旧的要快得多。