Skip to main content
 首页 » 编程设计

python之从特殊格式的文本文件中读取数据

2025年05月04日9虾米姐

我正在使用 Ashwini Chaudhary 友善建议的这种方法,将数据从特定格式的文本文件分配给字典。

keys = map(str.strip, next(f).split('Key\t')[1].split('\t')) 
words = map(str.strip, next(f).split('Word\t')[1].split('\t')) 

文本文件的行标题后跟值,由 \t 字符分隔。

示例 1:

Key      a 1  b 2  c 3  d 4 
Word     as   box  cow  dig 

如何更改我的代码而不是读取文件中的所有行,而只读取特定行?我不想阅读的额外行应该被忽略:

示例 2 - 忽略 LineHere 和 OrHere 行:

LineHere  w    x    y    z 
Key       a 1  b 2  c 3  d 4 
OrHere    00   01   10   11 
Word      as   box  cow  dig 

或者,如果我想读取标题为“Word”的行 XOR“Letter”,则以文件中恰好出现的行为准。因此扫描示例 1 或 2 的代码也适用于:

示例 3 - 我想读取 Key 和 Letter 行:

LineHere  w    x    y    z 
Key       a 1  b 2  c 3  d 4 
OrHere    00   01   10   11 
Letter    A    B    C    D 

请随时对问题提出批评意见,我很乐意重新措辞/澄清问题。

作为引用,前体question链接在这里

非常感谢,

亚历克斯

请您参考如下方法:

像这样:

import re 
with open('abc') as f: 
    for line in f: 
        if line.startswith('Key'): 
            keys = re.search(r'Key\s+(.*)',line).group(1).split("\t") 
        elif line.startswith(('Word','Letter')): 
            vals = re.search(r'(Word|Letter)\s+(.*)',line).group(2).split("\t") 
 
    print dict(zip(keys,vals)) 

abc:

LineHere  w    x    y    z 
Key       a 1  b 2  c 3  d 4 
OrHere    00   01   10   11 
Word      as   box  cow  dig 

输出是:

{'d 4': 'dig', 'b 2': 'box', 'a 1': 'as', 'c 3': 'cow'} 

abc:

LineHere  w    x    y    z 
Key       a 1  b 2  c 3  d 4 
OrHere    00   01   10   11 
Letter    A    B    C    D 

输出是:

{'d 4': 'D', 'b 2': 'B', 'a 1': 'A', 'c 3': 'C'}