繁体   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