【问题标题】:Reading data from specially formatted text file从特殊格式的文本文件中读取数据
【发布时间】:2013-07-05 21:42:20
【问题描述】:

我正在使用 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 - 忽略 LineHereOrHere 行:

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 - 我想阅读 KeyLetter 行:

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链接在这里

非常感谢,

亚历克斯

【问题讨论】:

  • 请说明,什么是f。我认为这是一个文件对象。也不清楚你的意思是什么特定的异常('我会做些什么来处理以下异常')?
  • @sergzach 我现在已经编辑了这个问题。现在清楚了吗?
  • 为什么将“您不想阅读的额外行”称为“例外”?您的意思是:“如何更改我的代码不读取文件中的所有行,而只读取特定行?”?
  • 'Key'行数据用空格隔开,'Word'行数据用制表符隔开?
  • @sergzach 是的,这就是我的意思。我已经更新了问题

标签: python exception exception-handling text-files


【解决方案1】:

类似这样的:

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'}

【讨论】:

    【解决方案2】:
    ss = '''LineHere  w    x    y    z
    Key       a 1  b 2  c 3  d 4
    OrHere    00   01   10   11
    Word      as   box  cow  dig
    '''
    import re
    
    rgx = re.compile('Key +(.*)\r?\n'
                     '(?:.*\r?\n)?'
                     '(?:Word|Letter) +(.*)\r?\n')
    
    mat = rgx.search(ss)
    keys = mat.group(1).split(' ')
    words = mat.group(2).split('\t')
    

    您将通过阅读文件获得ss

    with open (filename) as f:
        ss = f.read()
    

    编辑

    好吧,如果所有行都有用制表符分隔的数据,你可以这样做:

    ss = '''LineHere  w\tx\ty\tz
    Key       a 1\tb 2\tc 3\td 4
    OrHere    00\t01\t10\t11
    Word      as\tbox\tcow\tdig
    '''
    import re
    
    rgx = re.compile('Key +(.*)\r?\n'
                     '(?:.*\r?\n)?'
                     '(?:Word|Letter) +(.*)\r?\n')
    
    print  dict(zip(*map(lambda x: x.split('\t'),
                         rgx.search(ss).groups())))
    

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 2017-08-06
      • 2017-08-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      相关资源
      最近更新 更多