【问题标题】:Making dictionaries for each sub folder为每个子文件夹制作字典
【发布时间】:2019-01-17 10:53:49
【问题描述】:

我想为主文件夹中的所有子文件夹制作单独的字典。

我有一个包含子文件夹的文件夹,其中有 .txt 文件,我将其中的“描述”隔离并添加到字典中。

我可以将它用于整个文件夹,但不能按子文件夹分开。

子文件夹结构如下:

├───Locatie_5
│   ├───Stacked_Batch_1
│   ├───Stacked_Batch_2_Top_Bottom
│   ├───Stacked_Loc5_Hab1_05mm
│   ├───Stacked_Loc5_Hab1_1mm
│   ├───Stacked_Loc5_Hab_General_Somesinglesmissingstill
│   └───Stacked_Loc_5_Hab2_Ishetwel5niet4
├───Stacked_Half_loc_4_Hab6_Half_loc_2_4
├───Stacked_Last_Session_Rest
├───Stacked_locatie_2_4
├───Stacked_Loc4_Hab6_25mm
└───Stacked_Locatie_2

理想的输出字典应该以文件夹命名(如果大小写后跟子文件夹),请列出在文件夹的 .txt 文件中找到的宏无脊椎动物分类名称及其出现的次数,如下所示:

  • Lo​​catie_5_Stacked_Batch_1 = {"Anisus_vortex": "4", "Bithynia_tentaculata": "2", ...}
  • Lo​​catie_5_Stacked_Batch_2_Top_Bottom = {"Anisus_vortex": "7", "Bithynia_tentaculata": "3", ...}
  • Stacked_Half_loc_4_Hab6_Half_loc_2_4 = {“Anisus_vortex”:“0”,“Bithynia_tentaculata”:“25”,...}
    • 等等……

在下面的代码中从主文件夹中获取所有描述,并将其子文件夹集中到一个字典中。我认为至少从第 7 行中的目录循环作为下一步是明智的。
在循环中创建字典并从那里获取文件夹路径作为字符串并分配对我来说也是有意义的它作为字典名称。

所以我想要的是以下内容:

  • 每个子文件夹的字典
  • 在每个字典中,“描述”加上来自该子文件夹的计数
  • 理想情况下,字典名称应该是或包含子文件夹名称。

我该怎么做?

附注:我只需要获取描述和计数,并知道他们最终从哪些文件夹将它们放入另一个文件(.txt、工作表或数据库),所以也许有不同的解决方案而不是先将它们添加到字典中?

import os
import re

taxa_Counts = dict()

for subdir, dirs, files in os.walk("D:/MacroInvertebrates_Stacked"):
    for dir in dirs:
        for file in files:
            #print os.path.join(subdir, file)
            filepath = subdir + os.sep + file

            if not filepath.endswith(".txt"):
                continue

            Current_File = open(filepath)
            for line in Current_File:
                line = line.rstrip()
                #print(line)
                if line.startswith("Description"):
                    taxa = line.split()[2:3]

                    #print(line)
                    #print(Taxon)
                    for taxon in taxa:
                        taxa_Counts[taxon]=taxa_Counts.get(taxon,0) +1 

print(taxa_Counts)

【问题讨论】:

  • 提供您期望的示例输出以避免任何歧义。有可能在子文件夹中有子文件夹的地方嵌套。使用目录中的终端/cmd 中的“树”命令显示您的子文件夹结构。
  • @RohithRNair 已编辑

标签: python-3.x dictionary directory-structure


【解决方案1】:

我只对第一部分进行了修改,因为您的描述提取部分正在工作。

请在下面找到 python 3 的实现。我还没有尝试过,所以如果它不起作用,请告诉我。

import os

root_folder = r'D:/MacroInvertebrates_Stacked'
content = {}

for root, dirs, files in os.walk(root_folder):
    for subdir in dirs:
        content[os.path.join(root, subdir)] = []
    content[root] = files

list_of_dicts = []

for folder, filenames in list(content.items()):
    dict_name = string(os.path.relpath(folder, root_folder)).replace('\\', '_')
    dict_name = {}
    for filename in filenames:
        if filename.endswith('.txt'):
           with open(filename) as f:
                for line in f:
                    line = line.rstrip()
                    if line.startswith("Description"):
                        taxa = line.split()[2:3]
                        for taxon in taxa:
                            dict_name[taxon]=dict_name.get(taxon,0) +1 
    list_of_dicts.append(dict_name)

print(list_of_dicts)

list_of_dicts 包含与每个子文件夹对应的字典名称以及其中的计数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2019-03-17
    • 1970-01-01
    相关资源
    最近更新 更多