Python2.7将Unicode字典与Unicode Lis相交

2024-09-27 23:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用集合和intersect方法来查找文件路径的unicode列表中哪些元素中包含特定字符。我们的目标是用其他字符替换这些字符,所以我制作了一个键和值的字典,其中键是要替换的内容,值是要替换的内容。然而,当我试图生成一个包含要替换的字符的路径交集时,结果是一个空集。我做错什么了?我有这个for循环,但我想使它尽可能有效。感谢您的反馈!你知道吗

代码:

# -*- coding: utf-8 -*-

import os

def GetFilepaths(directory):
    """
    This function will generate all file names a directory tree using os.walk.
    It returns a list of file paths.
    """
    file_paths = []
    for root, directories, files in os.walk(directory):
        for filename in files:
            filepath = os.path.join(root, filename)
            file_paths.append(filepath)
    return file_paths

# dictionary of umlauts (key) and their replacements (value)
umlautDictionary = {u'Ä': 'Ae',
                    u'Ö': 'Oe',
                    u'Ü': 'Ue',
                    u'ä': 'ae',
                    u'ö': 'oe',
                    u'ü': 'ue'
                    }

# get file paths in root directory and subfolders
filePathsList = GetFilepaths(u'C:\\Scripts\\Replace Characters\\Umlauts')
print set(filePathsList).intersection(umlautDictionary)

Tags: ofin路径内容forosrootfiles
2条回答

filePathsList是字符串列表:

[u'file1Ä.txt', u'file2Ä.txt', ...]

umlautDictionary正在用作键序列:

{u'Ä':..., ...}

交叉点为空,因为字符串u'Ä'未出现在字符串列表中。您正在比较u'Ä'和u'file1Ä.txt',两者不相等。Set intersection不会检查子字符串。你知道吗

既然您想用所需的字符替换文件名中的unicode字符,我建议采用以下方法:

umlautDictionary = {u'\xc4': u'Ae'}
filePathsList = [u'file1Ä.txt', u'file2Ä.txt']

words = [w.replace(key, value) for key, value in umlautDictionary.iteritems() for w in filePathsList]

输出:

[u'file1Ae.txt', u'file2Ae.txt']

您必须以u'\xc4'的形式为u'Ä'存储unicode字符,以此类推。你知道吗

相关问题 更多 >

    热门问题