[英]How to find and replace X lines in one text file with Y lines in another text file?
我问了这个问题: 如何在文本文件中查找和替换多行? 但是我的问题最终还是不清楚,所以我想再问一个更具体的问题。
我有Python 2.7。
我有三个文本文件, data.txt
, find.txt
和replace.txt
。
data.txt
大约是1MB大文件,有数千行。 现在,我有一个find.txt
包含我想找到行的X号文件data.txt
,并与行的Y个取代replace.txt
X和Y可以是相同的数,也可能不会。
例如:
data.txt
pumpkin
apple
banana
cherry
himalaya
skeleton
apple
banana
cherry
watermelon
fruit
find.txt
apple
banana
cherry
replace.txt
1
2
3
4
5
因此,在上面的示例中,我想搜索数据中所有出现的apple
, banana
和cherry
,并在其位置插入1,2,3,4,5
。
因此,生成的data.txt
如下所示:
pumpkin
1
2
3
4
5
himalaya
skeleton
1
2
3
4
5
watermelon
fruit
或者,如果行数replace.txt
均小于的find.txt
:
pumpkin
1
2
himalaya
skeleton
1
2
watermelon
fruit
我在使用正确的方法时遇到了一些麻烦,因为我的data.txt
约为1MB,所以我想尽可能地提高效率。 一种愚蠢的方法是将所有内容连接到一个长字符串中,然后使用replace
,然后输出到新的文本文件中,以便恢复所有换行符。
data = open("data.txt", 'r')
find = open("find.txt", 'r')
replace = open("replace.txt", 'r')
data_str = ""
find_str = ""
replace_str = ""
for line in data: # concatenate it into one long string
data_str += line
for line in find: # concatenate it into one long string
find_str += line
for line in replace:
replace_str += line
new_data = data_str.replace(find, replace)
new_file = open("new_data.txt", "w")
new_file.write(new_data)
但是对于像我这样的大数据文件来说,这似乎是如此令人费解和低效。
我想看到的东西的伪代码:
像这样:
(x,y) = find_lines(data.txt, find.txt) # returns line numbers in data.txt that contains find.txt
replace_data_between(x, y, data.txt, replace.txt) # replaces the data between lines x and y with replace.txt
def find_lines(...):
location = 0
LOOP1:
for find_line in find:
for i, data_line in enumerate(data).startingAtLine(location):
if find_line == data_line:
location = i # found possibility
for idx in range(NUMBER_LINES_IN_FIND):
if find_line[idx] != data_line[idx+location] # compare line by line
#if the subsequent lines don't match, then go back and search again
goto LOOP1
如您所见,我在逻辑上遇到了麻烦。 有人可以指出我正确的方向吗?
如果文件足够小,可以在内存中执行此操作...
我将首先映射find:replace关系:
find_replace_dict = {find_string:replace_string}
然后我将浏览数据文件...
of = open('output_file','wt')
for line in data_file:
if line in find_replace_dict.keys():
of.write(find_replace_dict[line])
else:
of.write(line)
of.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.