nob*_*are 5 python string replace file
我正在运行Python 2.7.
我有三个文本文件:data.txt,find.txt,和replace.txt.现在,find.txt包含我要搜索的几行,data.txt并用该内容替换该部分replace.txt.这是一个简单的例子:
data.txt中
pumpkin
apple
banana
cherry
himalaya
skeleton
apple
banana
cherry
watermelon
fruit
Run Code Online (Sandbox Code Playgroud)
find.txt
apple
banana
cherry
Run Code Online (Sandbox Code Playgroud)
replace.txt
1
2
3
Run Code Online (Sandbox Code Playgroud)
所以,在上面的例子中,我要搜索的所有出现apple,banana以及cherry在数据和更换这些线路1,2,3.
我遇到了一些正确的方法,因为我data.txt大约1MB,所以我希望尽可能高效.一种愚蠢的方法是将所有内容连接成一个长字符串并使用replace,然后输出到新的文本文件,以便恢复所有换行符.
import re
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)
Run Code Online (Sandbox Code Playgroud)
但对于像我这样的大型数据文件来说,这似乎是如此复杂和低效.此外,该replace功能似乎已被弃用,因此不太好.
另一种方法是逐行扫描并跟踪您找到匹配的线.
像这样的东西:
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
Run Code Online (Sandbox Code Playgroud)
我知道,没有完全形成的代码.我甚至不知道是否可以在某些行上或某些行之间搜索特定行的文件,但是我再次对它的逻辑感到有些困惑.做这个的最好方式是什么?
谢谢!
如果文件很大,你要read和write 一次在一个行,所以整个事情是不是一次加载到内存中。
# create a dict of find keys and replace values
findlines = open('find.txt').read().split('\n')
replacelines = open('replace.txt').read().split('\n')
find_replace = dict(zip(findlines, replacelines))
with open('data.txt') as data:
with open('new_data.txt', 'w') as new_data:
for line in data:
for key in find_replace:
if key in line:
line = line.replace(key, find_replace[key])
new_data.write(line)
Run Code Online (Sandbox Code Playgroud)
编辑:我将代码更改为,read().split('\n')而不是readliens()这样,因此\n不包含在查找和替换字符串中