簡體   English   中英

如何在另一個文本文件中的Y行中查找和替換一個文本文件中的X行?

[英]How to find and replace X lines in one text file with Y lines in another text file?

我問了這個問題: 如何在文本文件中查找和替換多行? 但是我的問題最終還是不清楚,所以我想再問一個更具體的問題。

我有Python 2.7。

我有三個文本文件, data.txtfind.txtreplace.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

因此,在上面的示例中,我想搜索數據中所有出現的applebananacherry ,並在其位置插入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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM