这是我的第一篇文章,也是编程的新手,所以请原谅我在提问时遇到的新手错误:
我有两个表格格式的文件:
IDs.txt
只是一个ID列表,如下所示:
1
2
3
4
7
dictionary_FE.txt
是一个包含2列的排序字典,这些列是制表符分隔的,如下所示:
1 a
2 b
5 h
7 g
其中键与值相关联。我想编写一个python代码来获取一个新文件,该文件获取IDs.txt
中的ID并在dictionary_FE.txt
中查找它们。并非IDs.txt
中的所有ID都在dictionary_FE.txt
中。我想要一个看起来像这样的文件:
File3.txt
作为输出:
1 a
2 b
3 'not found'
4 'not found'
7 g
以下是我写的:
#!/usr/bin/env python
infile1=open("dictionary_FE.txt", "r")
infile2=open("IDs.txt", "r")
F=infile1.readlines()
for item in infile2.readlines():
item=item.strip()
for line in F:
line=line.strip()
line=line.split('\t')
ide=line[1]
if item == ide:
print line[0]+"\t"+item
我得到一个空白输出。
答案 0 :(得分:0)
就是这样。
file2dict = {}
with open('File2.txt', 'r') as f:
for line in f.readlines():
l = line.split()
file2dict[l[0]] = l[1]
with open('File1.txt', 'r') as f:
with open('File3.txt', 'w') as f3:
for line in f.readlines():
l = line.split()
if l[0] in file2dict:
f3.write('%s %s\n' %(l[0], file2dict[l[0]]))
else:
f3.write("%s 'not found'\n" % l[0])
答案 1 :(得分:0)
table = {}
with open('File2.txt') as f_in: # Generates the dictionary
for line in f_in:
line = line.strip()
table[line.split('\t')[0]] = line.split('\t')[1]
with open('File1.txt') as f_1, open('File3.txt', 'w') as f_2: # Matches against the dictionary
for line in f_1:
key = line.strip()
if key in table:
f_2.write('%s\t%s\n'%(key,table[key]))
else:
f_2.write("%s\t'not found'\n"%key)