簡體   English   中英

使用循環在 file2 中從 file1 中搜索名稱並寫入 file3

[英]Using loops to search for names from file1 in file2 and writing to file3

我是 Python 的新手,有點想把頭發拉出來。 我已經嘗試了幾個小時的幾件事,但沒有運氣。

我認為這很簡單,希望如此。 我正在嘗試通過在讀取后剝離換行符來從 file2 中的 file1 中搜索名稱。 然后匹配。 如果找到我正在嘗試將整行從 file2 寫入 file3。 如果沒有找到,則只將名稱寫入 file3。

文件1:

Abigail
Alexa
Jamie

文件2:

Abigail,infoA,infoB,InfoC
John,infoA,infoB,InfoC
Jamie,infoA,infoB,InfoC

文件3:

Abigail,infoA,infoB,InfoC
Alexa
Jamie,infoA,infoB,InfoC

測試數據文件1:

阿比蓋爾
安德森
一月

詹西斯
拉里
鮑勃
鮑比
雪莉
沙龍

測試數據文件2:

阿比蓋爾,信息A,信息B,信息C
安德森,信息A,信息B,信息C
一月,信息A,信息B,信息C
詹西斯,infoA,infoB,infoC
拉里,信息A,信息B,信息C
鮑勃,信息A,信息B,信息C
鮑比,信息A,信息B,信息C
沙龍,信息A,信息B,信息C

此版本有效,但僅讀取和寫入第一個實例。

import re

f1 = open("file1.txt", "r")
f2 = open("file2.txt", "r")
f3 = open("file3.txt", "w")

for nameinfo in f1:
    nameinfo = nameinfo.rstrip()

    for listinfo in f2:
        if re.search(nameinfo, listinfo):
            f3.write(listinfo)
        else
            file3.write(nameinfo)

這個版本有效,但它在匹配之間循環時一遍又一遍地寫下名稱(沒有匹配)。

import re

f1 = open("file1.txt", "r")
f2 = open("file2.txt", "r")
f3 = open("file3.txt", "w")

list2 = file2.readlines()

for nameinfo in file1:
    nameinfo = gameInfo.rstrip()

    for listinfo in list2:
        if re.search(nameinfo, listinfo):
            file3.write(listinfo)
        else
            file3.write(nameinfo)

是否可以使用簡單的基本循環命令來達到預期的效果? 學習幫助將不勝感激。 我看到許多看起來非常復雜或難以理解的例子。 我剛剛開始,所以簡單的基本方法最適合學習基礎知識。

您的第二個解決方案不斷寫入未找到名稱的原因是因為它搜索file2.txt的每一行以查找匹配項並每次都添加到file3.txt中。

您可以做的是引入一個新變量來存儲您要添加到file3.txt的值,然后在循環之外是當您實際 append 將該值添加到您的文件時。

這是一個工作示例:

import re

# note the .read().split('\n') this creates a list with each line as an item in the list
f1 = open("file1.txt", "r").read().split('\n')
f2 = open("file2.txt", "r").read().split('\n')
f3 = open("file3.txt", "w")

for name in f1:
    # Edit: don't add aditional new line
    if name == '':
        continue

    f3_text = name

    for line in f2:
        # if we find a match overwrite the name value in f3_text
        # EDIT 2: don't match on partial names
        # These are called fstrings if you haven't seen them before
        # EDIT 3: using a regex allows us to use the ^ character which means start of line 
        # That way ron doesn't match with Sharon
        if re.search(rf"^{name},", line):
            f3_text = line

    # at this point f3_text is just the name if we never 
    # found a match or the entire line if a match was found
    f3.write(f3_text + '\n')

編輯:

增加新行的原因是,如果您查看f1 ,您會看到它實際上是 4 行

f1 = ['Abigail', 'Alexa', 'Jamie', '']

這意味着外部 for 循環運行了 4 次,並且在最后一次迭代f3_text = ''中附加了一個額外的新行。 我在 for 循環中添加了一個檢查來解決這個問題。

您也可以在不使用正則表達式模塊的情況下用純 Python 編寫它(如果您不想學習它的迷你語言):

with open("file1.txt", "r") as f:
    names = f.readlines()

with open("file2.txt", "r") as f:
    lines = f.readlines()

names = [name.strip() for name in names] #strip of all other unwanted characters

with open("file3.txt", "w") as f:
    for name in names:
        to_write = name + '\n'

        for line in lines:
            if name in line: #If we find a match rewrite 'to_write' variable adn Break the for loop
                to_write = line
                break

        f.write(to_write)

暫無
暫無

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

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