替换文件树中模式/名称的工具
anonymize-UU的Python项目详细描述
匿名UU
可以在on GitHub here找到此说明
压缩后的关键字或压缩的UU文件中的关键字替换或reguu中的模式更方便。它递归地遍历树,打开支持的文件,并用替换项替换找到的任何模式或关键字。除了内容之外,anomize_u还将取代文件/文件夹路径中的关键字/模式。在
结果将是原始文件树的复制或替换版本,并进行所有替换。在
目前,Anonymize_UU支持基于文本的文件,如.txt、.html、.json和.csv。假设为UTF-8编码。除了文本文件,Anonymize_u还可以处理(嵌套)zip存档。这些档案将被解压到一个临时文件夹,处理和压缩再次。在
安装
$ pip install anonymize_UU
使用
在代码中导入Anomymize类并创建一个匿名化对象,如下所示:
from anonymize import Anonymize
# refer to csv files in which keywords and substitutions are paired
anonymize_csv = Anonymize('/Users/casper/Desktop/keys.csv')
# using a dictionary instead of a csv file:
my_dict = {
'A1234': 'aaaa',
'B9876': 'bbbb',
}
anonymize_dict = Anonymize(my_dict)
# specifying a zip-format to zip unpacked archives after processing (.zip is default)
anonymize_zip = Anonymize('/Users/casper/Desktop/keys.csv', zip_format='gztar')
当使用csv文件时,anonymize_u将假设您的文件包含两列:左栏包含需要替换的关键字,右栏包含它们的替换。列标题是必需的,但不必遵循特定的格式。在
当只使用字典时(缺少pattern
参数),键将被它们的值替换。在
当关键字可以泛化为正则表达式时,性能可能会得到提高。Anynomize_UU将搜索这些模式并替换它们,而不是根据文件内容或文件/文件夹路径匹配整个dictionary/csv文件。示例:
^{pr2}$默认情况下区分大小写。可以使用flag
参数修改处理替换的正则表达式。它接受一个或多个变量which can be found here。多个变量由位OR(运算符|)组合而成。不区分大小写的替换示例:
anonymize_regex = Anonymize(my_dict, flags=re.IGNORECASE)
通过使用use_word_boundaries
参数(默认为False),算法忽略子字符串匹配。如果“ted”是字典中的键,而没有use_word_boundaries
,则算法将替换f.i.“created\u at”中的“ted”部分。您可以通过将use_word_boundaries
设置为True来解决此问题。它将把\b
-anchor放在regex模式或字典键周围。边界锚的优点在于“@”也被视为一个边界,因此电子邮件地址中的名称可以被替换。示例:
anonymize_regex = Anonymize(my_dict, use_word_boundaries=True)
Windows使用
创建zip存档时出现问题。确保您以管理员身份运行anonymize_UU。在
复制与替换
Anonymize_UU可以创建已处理文件树的副本或替换它。substitute
方法接受一个强制的源路径参数(文件、文件夹或zip存档文件的路径,可以是字符串或Path对象)和可选的目标路径参数(同样是字符串或Path对象)。目标需要引用一个文件夹。如果目标文件夹不存在,将创建它。在
当提供target参数时,anonymize_u将在目标文件夹中创建一个经过处理的源副本。当省略目标参数时,源将被它的处理版本覆盖:
# process the datadownload.zip file, replace all patterns and write
# a copy to the 'bucket' folder.
anonymize_regex.substitute(
'/Users/casper/Desktop/datadownload.zip',
'/Users/casper/Desktop/bucket'
)
# process the 'download' folder and replace the original by its processed
# version
anonymize_regex.substitute('/Users/casper/Desktop/download')
# process a single file, and replace it
anonymize_regex.substitute('/Users/casper/Desktop/my_file.json')
托多
测试;)
- 项目
标签: