python - 使用 trie 在 python 中创建目录结构

标签 python directory-structure trie

我有一个文件名列表:

文件名 = ["111", "112", "1341", "2213", "2131", "22222", "11111"]

应该以目录结构进行组织,并且一个目录中的最大文件数不应大于2。因此,我制作一个前缀树(trie,下面的代码)存储在字典中,以前缀作为键,如果子树中的文件数量不超过最大值,则使用 'end' :

trie = make_trie(文件名, max_freq=2)

trie
{'1': {'1': {'1': 'end', '2': 'end'}, '3': 'end'},'2': {'1': 'end', '2': 'end'}}

对于每个文件名,我都会在 trie 中进行查找(下面的代码)并相应地构建路径:

for f in filenames:
    print("Filename: ", f, "\tPath:", get_path(f, trie))

Filename:  111  Path: 1/1/1/
Filename:  112  Path: 1/1/2/
Filename:  1341         Path: 1/3/
Filename:  2213         Path: 2/2/
Filename:  2131         Path: 2/1/
Filename:  22222        Path: 2/2/
Filename:  11111        Path: 1/1/1/

这很有效,但由于我对 trie (make_trie) 和查找 (get_path) 的简单实现,这变得令人望而却步。我的猜测是我应该采用一个高效的现有 trie 实现,例如 pytrie 和 datrie,但我真的不知道如何制作阈值为 2 的 trie对于后缀的数量,所以我对如何使用这些包有点困惑,例如:

import datrie
tr = datrie.Trie(string.digits) # make trie with digits
for f in filenames:
    tr[f] = "some value" # insert into trie, but what should be the values??

tr.prefixes('111211321') # I can look up prefixes now, but then what?

如何使用现有的快速 trie 实现来创建我的目录结构?

我对 trie 和 Lookup 的天真实现:

def make_trie(words, max_freq):
    root = dict()
    for word in words:
        current_dict = root
        for i in range(len(word)):
            letter = word[i]
            current_prefix = word[:i+1]
            prefix_freq = sum(list(map(lambda x: x[:i+1]==current_prefix, words)))
            if prefix_freq > max_freq:
                current_dict = current_dict.setdefault(letter, {})
            else:
                current_dict = current_dict.setdefault(letter, "end")
                break
    return root

def get_path(image_id, trie):
    result = ""
    current_dict = trie
    for i in range(len(image_id)):
        letter = image_id[i]
        if letter in current_dict:
            result += letter + "/"
            if current_dict[letter] == "end":
                break
            current_dict = current_dict[letter]
    return result

最佳答案

使用os.makedirs,这可以工作。

import os

def create_dir_structure(filenames):
    for filename in filenames:
        os.makedirs(
            '/'.join(e for e in str(filename))
        )


create_dir_structure(
    ['1111', '1123']
)

如果您希望看到任何不同的行为,请在评论中告诉我

关于python - 使用 trie 在 python 中创建目录结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59408829/

相关文章:

python - 如何将 mechanize.Browser() cookie 保存到文件?

php - 访问root以外文件的方法

linux - 文件/目录权限尾随 + ( drwxr-xr-x+ )

python - 从 zip 中提取某些文件但不是完整的目录

c++ - Trie 中的最短路径

Python:如何将 Pandas Dataframe 行值转换为单独的列?

python - Anaconda + Apache + mod_wsgi + Ubuntu

Scala - TrieMap 与 Vector

java - 如何在 trie 中存储和搜索字典

python - 在 PyQT 和 Boost.Python 之间共享小部件