如何在一行文件中搜索正确的单词

时间:2014-07-31 15:41:54

标签: python

我有文本文件file1.txt。其中包含

test_file_work(list: 2, Result =0)

test_file_work_list(list: 5, Result =0)

test_file_work_list(list: 6, Result =0)

test_file_work(list: 2, Result =5)

test_file_work_list(list: 6, Result =0)

如何在文件result = 0

中找到所有行

我的代码:

fo=open("file1.txt","r")
for line in fo.readlines():
    if re.search(r"test_(.*)(list)(.*),result=0,line):
        print "ok"
    else:
        print "mismatch"

3 个答案:

答案 0 :(得分:2)

如果线条图案始终相同,则可以执行以下操作:

fo=open("file1.txt","r")
for line in fo.readlines():
    if 'Result =0' in line:
        print "ok"
    else:
        print "mismatch"

答案 1 :(得分:0)

print [line for line in open("somefile") if "Result =0" in line]

可能是最简单的方式......至少是imho

有许多方法可以实现这一目标

虽然我怀疑你想要更像

的东西
a_generator = (line for line in open("somefile") if "Result =0" in line)
print [re.findall("list: \d+",line) for line in a_generator]

答案 2 :(得分:0)

with open("in.txt","r") as fo: # use with to open files, it closes them automatically
    for line in fo.readlines():
        if line.strip(): # skip empty lines
            if line.rstrip()[-2] == '0': # remove `\n`
                print "ok"
            else:
                print "mismatch"

如果你想检查字符串中的两个子串,你就不需要了:

with open("in.txt","r") as fo: # use with to open files, it closes them automatically
        for line in fo.readlines():
                if "Result =0" in line and "test_file_work_list" in line : 
                    print "ok"
                else:
                    print "mismatch"

或使用if all(x in line for x in ["Result =0","test_file_work_list"])

如果要提取行:

with open("Hello.txt","r") as fo:
    f = fo.readlines()
    lines = [ele for ele in f if  all(y in ele for y in ["Result =0","test_file_work_list"])]