我正在尝试使用集合和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)
filePathsList是字符串列表:
umlautDictionary正在用作键序列:
交叉点为空,因为字符串u'Ä'未出现在字符串列表中。您正在比较u'Ä'和u'file1Ä.txt',两者不相等。Set intersection不会检查子字符串。你知道吗
既然您想用所需的字符替换文件名中的unicode字符,我建议采用以下方法:
输出:
您必须以
u'\xc4'
的形式为u'Ä'
存储unicode字符,以此类推。你知道吗相关问题 更多 >
编程相关推荐