【发布时间】:2014-03-05 12:36:27
【问题描述】:
我问了这个问题:How to find and replace multiple lines in text file? 但我的问题最终不清楚,所以我要求另一个更具体的问题。
我有 Python 2.7。
我有三个文本文件,data.txt、find.txt 和 replace.txt。
data.txt 是大约 1MB 的大文件,有几千行。现在,我有一个 find.txt 文件,其中包含我想在 data.txt 中找到的 X 行,并用 replace.txt 中的 Y 行替换 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.txt和replace.txt,查找dict。然后通过data.txt并用查找字典中的值替换每一行(如果存在)。您需要更具体地了解find和replace.txt的布局,才能获得更具体的帮助。 -
没有 1:1 映射,
find到replace的映射是什么?而不是文本文件,你能给我们一个 python 对象吗? -
当 X 和 Y 不相同时,您希望发生什么?当 X > Y 和 X
-
@Totem:感谢您的 cmets。我编辑了我的问题,希望能提供更多信息。
-
@roippi:感谢您的 cmets。我编辑了我的问题,希望能提供更多信息。
标签: python string file replace