【发布时间】:2019-06-16 11:32:52
【问题描述】:
我有一个大文本文件。我将该文件分块为具有一定大小的小文件。以下是我得到的一个例子:
import math
import os
numThread = 4
inputData= 'dir\example.txt'
def chunk_files():
nline = sum(1 for line in open(inputData,'r', encoding='utf-8', errors='ignore'))
chunk_size = math.floor(nline/int(numThread ))
n_thread = int(numThread )
j = 0
with open(inputData,'r', encoding='utf-8', errors='ignore') as file_:
for i, line in enumerate(file_):
if (i + 1 == j * chunk_size and j != n_thread) or i == nline:
out.close()
if i + 1 == 1 or (j != n_thread and i + 1 == j * chunk_size):
chunk_file = '_raw' + str(j) + '.txt'
if os.path.isfile(chunk_file):
break
out = open(chunk_file, 'w+', encoding='utf-8', errors='ignore')
j = j + 1
if out.closed != True:
out.write(line)
if i % 1000 == 0 and i != 0:
print ('Processing line %i ...' % (i))
print ('Done.')
这是文本文件中的文本示例:
190219 7:05:30 line3 success
line3 this is the 1st success process
line3 this process need 3sec
200219 9:10:10 line2 success
line2 this is the 1st success process
由于块的大小,我获得了各种形式的拆分文本。像这样:
190219 7:05:30 line3 success
line3 this is the 1st success process
line3 this process need 3sec
200219 9:10:10 line2 success
line2 this is the 1st success process
我需要使用正则表达式 reg= re.compile(r"\b(\d{6})(?=\s\d{1,}:\d{2}:\d{2})\b") 拆分后跟日期时间,如下所示:
190219 7:05:30 line3 success
line3 this is the 1st success process
line3 this process need 3sec
200219 9:10:10 line2 success
line2 this is the 1st success process
我试过Python: regex match across file chunk boundaries。但似乎我无法根据我的问题进行调整。
谁能帮我将正则表达式放入 chunk_files 函数中?提前致谢
【问题讨论】:
标签: python regex python-3.x filesplitting