【问题标题】:Extracting specific information using iterator and re python使用迭代器和重新python提取特定信息
【发布时间】:2017-06-16 12:11:57
【问题描述】:

我有一个程序可以告诉我今天谁过生日。
我的姓名和生日存储在一个名为 data.txt 的文本文件中。
以下是 data.txt 的示例:

Master 13/12 
Monkey 16/06
Michael 16/06
mike  01/05
Minita 24/06
Mom 12/06

这是程序:

from __future__ import print_function
import time

logic = time.strftime("%d/%m")
err_occur = []                        
pattern = re.compile(logic, re.IGNORECASE)
try:
    with open ('data.txt', 'rt') as in_file:         
        for linenum, line in enumerate(in_file):        
            if pattern.search(line) != None:         
                err_occur.append((linenum, line.rstrip('\n')))
                for linenum, line in err_occur:             
                    print("Line ", linenum, ": ", line, sep='')
except IOError:
    print ("data.txt Not found")

如果我运行这个程序并且今天的日期是 16/06,它的输出应该是

Line 3: Monkey 16/06
Line 4: Michael 16/06

但是它显示给我的输出只是

Line 3: Monkey 16/06

我猜for...in 语句无效?
他们不应该循环工作吗?

我学习python才几天。我还没有完全理解迭代器。因此,如果您能用外行的方式解释我的错误,那将非常有帮助。

编辑-感谢@zwer 指出我的错误,感谢@Coldspeed 提供更有效的解决方案。

【问题讨论】:

    标签: python regex python-2.7 iterator


    【解决方案1】:

    有一种更简单的方法可以一一获取这些匹配的行。您可以使用re.finditer。它返回一个匹配的生成器:

    from __future__ import print_function
    import re
    import time
    
    s = open('data.txt', 'rt').read()
    
    logic = time.strftime("%d/%m")
    err_occur = []                        
    for m in re.finditer('(.*?)[\s]*' + logic, s, re.M | re.IGNORECASE):
        print(m.group(0))
    

    输出

    Monkey 16/06
    Michael 16/06
    

    这不会在输出中为您提供Line x。如果你愿意,你可能需要稍微改变一下。

    【讨论】:

    • 考虑到我会将所有生日都放在data.txt 中,我认为这种方法行不通。因此,我建议您将第一行更改为s = open('data.txt', 'rt').read() EDIT-我刚刚看到您已经这样做了
    • @HellfireCharchitPb 完成。
    【解决方案2】:

    为什么在读取文件时要进行双循环?如果您想按照自己的方式构建它,只需打印出匹配的行:

    from __future__ import print_function
    import re
    import time
    
    logic = time.strftime("%d/%m")
    err_occur = []
    pattern = re.compile(logic, re.IGNORECASE)
    try:
        with open ('data.txt', 'rt') as in_file:
            for linenum, line in enumerate(in_file):
                if pattern.search(line) != None:
                    line = line.rstrip("\n")
                    print("Line ", linenum + 1, ": ", line, sep='')
                    err_occur.append((linenum + 1, line))
    except IOError:
        print ("data.txt Not found")
    
    # Line 2: Monkey 16/06
    # Line 3: Michael 16/06
    

    【讨论】:

      猜你喜欢
      • 2021-03-25
      • 1970-01-01
      • 2013-08-19
      • 2013-11-22
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多