0

我是 Python 新手。

我有一个打印表格(及其内容)的字符串,如下所示

Name         At time Last  Inter\ Max    Logfile Location               Status  
                     time   val   log                                           
                           (mins) files                                         
------------ ------- ----- ------ ------ ------------------------------ ------- 
foo1           now   16:00   60   100    flash:/schedule/foo1/          Job     
                                                                        under   
                                                                        progress
foo2           now     -     60   100    -                              Waiting 
tech-support   now   16:00   60   100    flash:/schedule/tech-support/  Job     
                                                                        under   
                                                                        progress

我需要找出字符串“ Job under progress”出现在表中的次数。我试过了len( re.findall( pattern, string ) )len( re.findall("(?=%s)" % pattern, string) )但它们似乎都不起作用。

有更好的建议吗?

4

1 回答 1

3
data = """
Name         At time Last  Inter\ Max    Logfile Location               Status  
                     time   val   log                                           
                           (mins) files                                         
------------ ------- ----- ------ ------ ------------------------------ ------- 
foo1           now   16:00   60   100    flash:/schedule/foo1/          Job     
                                                                        under   
                                                                        progress
foo2           now     -     60   100    -                              Waiting 
tech-support   now   16:00   60   100    flash:/schedule/tech-support/  Job     
                                                                        under   
                                                                        progress
                                                                        """
import re
print len(re.findall("Job\s+under\s+progress", data))

输出

2

编辑: 如果它在同一行,你根本不需要正则表达式

data = """
Name         At time Last  Inter\ Max    Logfile Location               Status  
                     time   val   log                                           
                           (mins) files                                         
------------ ------- ----- ------ ------ ------------------------------ ------- 
foo1           now   16:00   60   100    flash:/schedule/foo1/          Job under progress
foo2           now     -     60   100    -                              Waiting 
tech-support   now   16:00   60   100    flash:/schedule/tech-support/  Job under progress
"""

print sum(1 for line in data.split("\n") if "Job under progress" in line)

输出

2
于 2013-10-28T06:21:13.390 回答