2017-08-10 84 views
0

我有多个带有ID和值的* .txt文件,我想创建一个唯一的字典。但是,某些文件中会重复某些ID,并且对于这些ID,我想要将这些值进行CONCATENATED。这是两个文件的示例(但我有一堆文件,所以我认为我需要glob.glob):(注意某个文件中的所有'值'具有相同的长度,所以我可以将' - '添加为。多次LEN(值)丢失从多个文本文件构建字典映射

文件1

ID01 
Hi 
ID02 
my 
ID03 
ni 

文件2

ID02 
name 
ID04 
meet 
ID05 
your 

欲望输出:(注意,当没有重复的ID,我要添加“ Na'或' - ',与len(value)相同)这是我的输出:

ID01 
Hi---- 
ID02 
myname 
ID03 
ni---- 
ID04 
--meet 
ID05 
--your 

我只想将输出存储在字典中。另外,我猜如果打开文件时打印文件,我可以知道打开哪个文件的顺序,对吧?

这是我有:(我不能连接我的价值观至今)

output={} 
list = [] 
for file in glob.glob('*.txt'):   
    FI = open(file,'r') 
    for line in FI.readlines(): 
     if (line[0]=='I'):  #I am interested in storing only the ones that start with I, for a future analysis. I know this can be done separating key and value with '\t'. Also, I am sure the next lines (values) does not start with 'I' 
      ID = line.rstrip() 
      output[ID] = '' 
      if ID not in list: 
       list.append(ID)  
     else: 
      output[ID] = output[ID] + line.rstrip() 

    if seqs_name in list: 
     seqs[seqs_name] += seqs[seqs_name] 

    print (file) 
    FI.close() 


print ('This is your final list: ') 
print (list) #so far, I am getting the right final list, with no repetitive ID 
print (output) #PROBLEM: the repetitive ID, is being concatenated twice the 'value' in the last file read. 

此外,如何添加“ - ”时,不重复ID?我将非常感谢您的帮助。

总结:当密钥在另一个文件中重复时,我无法连接值。如果密钥不重复,我想添加' - ',这样我以后可以打印文件名并知道某个ID在哪个文件中没有值。

回答

0

几个问题与您现有的代码:

  1. line[0] == 'ID'line[0]返回字符,所以这比较始终为false。改用str.startswidth(xxx)来检查一个字符串是否以xxx开头。

  2. 您没有正确检索ID之后的文本。最简单的方法是致电next(f)

  3. 您不需要第二个列表。此外,不要将变量list命名为阴影内置。


import collections 

output = collections.defaultdict(str) 
for file in glob.glob('*.txt'):   
    with open(file, 'r') as f: 
    for line in f: 
     if line.startswith('ID'): 
      try: 
       text = next(f) 
       output[line.strip()] += text.strip() + ' ' 
      except StopIteration: 
       pass 

print(output) 

它绝不会伤害到钓奇异常,则使用try-except

+0

好的,你的新版本正在工作:)。非常感谢! – gusa10

+0

如果您想在未连接值时添加' - '或'Na',该怎么办? – gusa10

+0

@ gusa10每个线程一个问题请;)你可以考虑标记这接受,如果它帮助。至于添加Na,您必须获取文本,然后检查文本是否也以ID开头。这意味着实际的文字不见了。 –