使用另一个文本文件(文本B)中的列表查找文本文件(文本a)中的名称,并在文本a(Python)中的名称旁边赋值

使用另一个文本文件(文本B)中的列表查找文本文件(文本a)中的名称,并在文本a(Python)中的名称旁边赋值,python,find,assign,names,Python,Find,Assign,Names,我是Python语言的新手,我需要你的帮助 我有两个不同的文本文件。让我们看看它们是Text_A.txt和Text_B.txt Text_A.txt包含名称列表,如下所示: 序列1序列2序列3序列4 序列5序列6序列7序列8 文本_B.txt包含一个名称列表,每行中都写有以下序列名称: 序列1 序列2 序列3 序列4 序列5 序列6 序列7 序列8 序列9 序列10 序列11 我想做的是在Text_B.txt中的序列名称旁边指定1,如果名称在Text_A.txt中。如果名称不在Text_A.tx

我是Python语言的新手,我需要你的帮助

我有两个不同的文本文件。让我们看看它们是Text_A.txt和Text_B.txt

Text_A.txt包含名称列表,如下所示:

序列1序列2序列3序列4 序列5序列6序列7序列8

文本_B.txt包含一个名称列表,每行中都写有以下序列名称:

序列1 序列2 序列3 序列4 序列5 序列6 序列7 序列8 序列9 序列10 序列11

我想做的是在Text_B.txt中的序列名称旁边指定1,如果名称在Text_A.txt中。如果名称不在Text_A.txt中,则在Text_B.txt中的序列名称旁边指定0

所以。。。使用上述示例的预期输出如下所示。应在每行中写入名称和相应的值:

序列_1;1. 序列2;1. 序列3;1. 序列4;1. 序列5;1. 序列_6;1. 序列7;1. 序列8;1. 序列9;0 序列10;0 序列11;0

我想在.txt格式的输出

我应该如何使用Python实现这一点

这里确实需要您的帮助,因为我在Text_A.txt和Text_B.txt文件中分别有3000多个和6000多个名称


非常感谢你

您可以执行以下操作

# read each file assuming that your sequence of strings 
# is the first line respectively
with open('Text_A.txt', 'r') as f:
    seqA = f.readline()
with open('Text_B.txt', 'r') as f:
    seqB = f.readline()

# remove end-of-line character
seqA = seqA.strip('\n')
seqB = seqB.strip('\n')

# so far, seqA and seqB are strings. split them now on tabs
seqA = seqA.split('\t')
seqB = seqB.split('\t')

# now, seqA and seqB are list of strings
# since you want to use seqA as a lookup, you should make a set out of seqA
seqA = set( seqA )

# now iterate over each item in seqB and check if it is present in seqA
# store result in a list
out = []
for item in seqB:
    is_present = 1 if item in seqA else 0
    out.append('{item}:{is_presnet}\n'.format(item=item,is_present=is_present))

# write result to file
with open('output.txt','w') as f:
    f.write( '\t'.join( out ) )

如果您的序列包含数百万个条目,您应该考虑一种更高级的方法。

请给出您试图解决此问题的代码部分。这将为其他人提供一种方法来发现您的代码中有哪些错误不起作用!嗨,迪卡,谢谢你的留言。。。我真的是一个初学者,所以我不知道从哪里开始…6000不是一个大数字,我的意思是不足以造成基本代码和基本硬件无法处理的困难。我想很多人会不同意这种方法,因为你需要通过谷歌的所有帮助,比如用python编写基本程序,如何在stackoverflow中过帐之前写入或读取文件等!当人们被卡住的时候,他们习惯于发帖!这既不是代码编写服务,也不是教程网站。非常感谢您的详细解释。我将仔细阅读并学习。请不要忘记标记那些对你有用的答案,并接受对你帮助最大的答案。