[英]how to search word in a line of file correct
I have the text file file1.txt. 我有文本文件file1.txt。 which contains lines as
其中包含行
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)
How to find in all the lines in the file result=0 如何在文件的所有行中查找result = 0
My code: 我的代码:
fo=open("file1.txt","r")
for line in fo.readlines():
if re.search(r"test_(.*)(list)(.*),result=0,line):
print "ok"
else:
print "mismatch"
If the lines pattern will be always the same you can do: 如果线条模式始终相同,则可以执行以下操作:
fo=open("file1.txt","r")
for line in fo.readlines():
if 'Result =0' in line:
print "ok"
else:
print "mismatch"
print [line for line in open("somefile") if "Result =0" in line]
is probably the simplest way ... at least imho 可能是最简单的方法了……至少恕我直言
there are many many ways to accomplish this though 虽然有很多方法可以做到这一点
although I suspect you want something more like 虽然我怀疑你想要更多类似的东西
a_generator = (line for line in open("somefile") if "Result =0" in line)
print [re.findall("list: \d+",line) for line in a_generator]
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"
If you want to check for two substrings in your string you don't need re: 如果要检查字符串中的两个子字符串,则无需重新输入:
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"
Or use if all(x in line for x in ["Result =0","test_file_work_list"])
或
if all(x in line for x in ["Result =0","test_file_work_list"])
使用if all(x in line for x in ["Result =0","test_file_work_list"])
If you want to extract the lines: 如果要提取行:
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"])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.