使用re
模块构造正则表达式:
regex = r"""
( # Capture in group #1
"[\w\s]+" # Three sequences of quoted letters and white space characters
\s+ # followed by one or more white space characters
"[\w\s]+"
\s+
"[\w\s]+"
\s+
)
"(\d{10,})" # Match a quoted set of at least 10 integers into group #2
(^^\s+\.\s+) # Match by two circumflex characters, whitespace and a period
# into group #3
(.*) # Followed by anything at all into group #4
"""
COMPILED_REGEX = re.compile(regex, re.VERBOSE)
接下来,我们需要定义一个回调函数(因为re.RegexObject.sub
需要回调)来处理替换:
def replace_callback(matches):
full_line = matches.group(0)
number_text = matches.group(2)
number_of_interest = int(number_text, base=10)
if number_of_interest > 2147483647:
return full_line.replace(number_of_interest, number_text[:3])
else:
return full_line
然后查找并替换:
fixed_data = COMPILED_REGEX.sub(replace_callback, YOUR_DATA)
如果您有 TB 的数据,您可能不想在内存中执行此操作 - 您需要打开文件然后对其进行迭代,逐行替换数据并将其写回另一个文件(毫无疑问加快速度的方法,但它们会使该技术的要点更难遵循:
# Given the above
def process_data():
with open("path/to/your/file") as data_file,
open("path/to/output/file", "w") as output_file:
for line in data_file:
fixed_data = COMPILED_REGEX.sub(replace_callback, line)
output_file.write(fixed_data)