【问题标题】:Build dict mapping from multiple text files从多个文本文件构建字典映射
【发布时间】:2017-08-10 06:02:27
【问题描述】:

我有多个带有 ID 和值的 *.txt 文件,我想创建一个唯一的字典。但是,某些 ID 在某些文件中重复,对于这些 ID,我想连接这些值。这是两个文件的示例(但我有一堆文件,所以我认为我需要 glob.glob):(注意某个文件中的所有“值”都具有相同的长度,所以我可以添加“-”为len(value) 多次丢失。

文件 1

ID01
Hi 
ID02 
my 
ID03 
ni

文件 2

ID02 
name
ID04 
meet 
ID05 
your

Desire 输出:(注意当没有重复的 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不重复时如何添加'-'?非常感谢您的帮助。

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

【问题讨论】:

    标签: python dictionary text-files glob string-concatenation


    【解决方案1】:

    您现有代码的几个问题:

    1. line[0] == 'ID':line[0] 返回一个字符,所以这个比较总是假的。请改用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 捕获奇怪的异常永远不会有什么坏处。

    【讨论】:

    • 如果你想在一个值没有连接的时候加上'-'或者'Na'怎么办?
    • @gusa10 每个线程一个问题;)如果有帮助,您可以考虑将其标记为已接受。至于添加Na,您必须获取文本,然后检查文本是否也以ID开头。这意味着缺少实际文本。
    • 我很抱歉我对这个网页的天真。谢谢您的回答。你能解释一下如何得到'NA'。我尝试使用“如果输出中的文本:”,但它似乎不起作用。谢谢
    • 我不明白你想要什么。你能打开一个新问题吗?在那里解释自己会更容易。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    相关资源
    最近更新 更多