簡體   English   中英

在另一個 .txt 文件中逐位搜索一個 .txt 文件的內容段並打印匹配行

[英]Search for content segments of one .txt file in another .txt file digit by digit and print matching lines

我有兩個 txt 文件:file1.txt 和 file2.txt。

File1.txt 包含以下內容:

12345678

File2.txt 包含以下內容:

34567999
23499899
13571234

我現在想查看 file1.txt 第 1 行的前 3 位數字(即“123”)。 我現在想去 file2.txt 並搜索這三個數字(“123”)。 當我在一行中按該順序找到這些數字時(即:第 3 行就是這種情況:1357 123 4),我想將此行寫入一個新文件:file_new.txt。

然后,如果在 file2.txt 中的所有行都從 file1.txt(“123”)中搜索了這個序列,我想在 file1.txt 中再移動一位,以便新的搜索查詢是“234”。 現在,我想再次轉到 file2.txt 以搜索所有包含“234”的序列,(即:第 2 行( 234 99899)和第 3 行(13571 234 ))。 由於第 3 行已包含在 file_new.txt 中,我只想將第 2 行寫入 file_new.txt。

我想繼續這個過程,搜索接下來的三位數字,直到在 file2.txt 中搜索到 file1.txt 中的整行。

有人可以幫我解決這個問題嗎?

您可以使用 readlines 將文本文件讀入列表,然后使用如下所示的 while 循環生成新列表 L。 然后,您可以將此列表 L 寫入文本文件。

with open(file1_path) as file1:
    search_string = file1.readlines()[0]

with open(file2_path) as file2:
    strings_to_search = file2.readlines()

L= []
n=0 
while n < len(search_string):
    for i in strings_to_search:
        if search_string[n:n+3] in i and i not in L:
            L.append(i)
        n +=1

我在這里得到了一個小解決方案:

f1 = open('file1.txt', 'r') # open in read mode

for digit in range(len(f1.readlines()[0])-2):
    threedigits = f1.readlines()[0][digit:digit+3] # This is the first three digits

    f2 = open('file2.txt', 'r') # open in read mode
    lines = f2.readlines() # we read all lines
    f2.close()
    file_new = []
    for i in lines:
        if firstthreedigits in i:
            file_new.append(i) # we add each lines containing the first three digits

    f3 = open('file_new.txt', 'w') # open in write mode
    for i in range(len(file_new)):
        f3.write(file_new[i]) # we write all lines with first three digits
    f3.close()

f1.close()

這應該給它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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