我有一个项目,我需要使用python将十几个正则表达式应用于大约100个文件。 4个多小时在网上搜索各种组合,包括"(merge | concatenate | stack | join | compile)python中的多个正则表达式#34;我还没有找到任何有关我需要的帖子。
对我来说这是一个中型项目。我需要几个较小的正则表达式项目,只需要在十几个文件中应用5-6个正则表达式模式。虽然这些对我的工作有很大的帮助,但是爷爸项目是一个应用100+搜索的文件,将字符串替换为我得到的任何新文件。 (某些语言的拼写惯例不是标准化的,能够快速处理文件会提高工作效率。)
理想情况下,正则表达式字符串需要由非程序员更新,但这可能超出了本文的范围。
这是我到目前为止所做的:
import os, re, sys # Is "sys" necessary?
path = "/Users/mypath/testData"
myfiles = os.listdir(path)
for f in myfiles:
# split the filename and file extension for use in renaming the output file
file_name, file_extension = os.path.splitext(f)
generated_output_file = file_name + "_regex" + file_extension
# Only process certain types of files.
if re.search("txt|doc|odt|htm|html")
# Declare input and output files, open them, and start working on each line.
input_file = os.path.join(path, f)
output_file = os.path.join(path, generated_output_file)
with open(input_file, "r") as fi, open(output_file, "w") as fo:
for line in fi:
# I realize that the examples are not regex, but they are in my real data.
# The important thing, is that each of these is a substitution.
line = re.sub(r"dog","cat" , line)
line = re.sub(r"123", "789" , line)
# Etc.
# Obviously this doesn't work, because it is only writing the last instance of line.
fo.write(line)
fo.close()
答案 0 :(得分:2)
这是你要找的吗?
不幸的是,您没有指定如何知道应该应用哪些正则表达式,因此我将它们放入元组列表中(第一个元素是正则表达式,第二个元素是替换文本)。
import os, os.path, re
path = "/Users/mypath/testData"
myfiles = os.listdir(path)
# its much faster if you compile your regexes before you
# actually use them in a loop
REGEXES = [(re.compile(r'dog'), 'cat'),
(re.compile(r'123'), '789')]
for f in myfiles:
# split the filename and file extension for use in
# renaming the output file
file_name, file_extension = os.path.splitext(f)
generated_output_file = file_name + "_regex" + file_extension
# As l4mpi said ... if odt is zipped, you'd need to unzip it first
# re.search is slower than a simple if statement
if file_extension in ('.txt', '.doc', '.odt', '.htm', '.html'):
# Declare input and output files, open them,
# and start working on each line.
input_file = os.path.join(path, f)
output_file = os.path.join(path, generated_output_file)
with open(input_file, "r") as fi, open(output_file, "w") as fo:
for line in fi:
for search, replace in REGEXES:
line = search.sub(replace, line)
fo.write(line)
# both the input and output files are closed automatically
# after the with statement closes