[英]OR in regular expression?
I have text file with several thousands lines. 我有几千行的文本文件。 I want to parse this file into database and decided to write a regexp.
我想将此文件解析为数据库并决定编写正则表达式。 Here's part of file:
这是文件的一部分:
blablabla checked=12 unchecked=1
blablabla unchecked=13
blablabla checked=14
As a result, I would like to get something like 结果,我想得到类似的东西
(12,1)
(0,13)
(14,0)
Is it possible? 可能吗?
最简单的方法是使用两个不同的正则表达式来拉出两个数字: r" checked=(\\d+)"
和r" unchecked=(\\d+)"
。
import re
lines = ["blablabla checked=12 unchecked=1", "blablabla unchecked=13"]
p1 = re.compile('checked=(\d)+\sunchecked=(\d)')
p2 = re.compile('checked=(\d)')
p3 = re.compile('unchecked=(\d)')
for line in lines:
m = p1.search(line)
if m:
print m.group(1), m.group(2)
else:
m = p2.search(line)
if m:
print m.group(1), "0"
else:
m = p2.search(line)
if m:
print "0", m.group(1)
import re
s = """blablabla checked=12 unchecked=1
blablabla unchecked=13
blablabla checked=14"""
regex = re.compile(r"blablabla (?:(?:checked=)(\d+))? ?(?:(?:unchecked=)(\d+))?")
for line in s.splitlines():
print regex.match(line).groups()
This gives you strings (or None
if not found), but the idea should be clear. 这为你提供了字符串(如果没有找到则为
None
),但这个想法应该是明确的。
An alternative approach: 另一种方法:
import sys
import re
r = re.compile(r"((?:un)?checked)=(\d+)")
for line in open(sys.argv[1]):
d = dict( r.findall(line) )
print d
Output: 输出:
{'checked': '12', 'unchecked': '1'}
{'unchecked': '13'}
{'checked': '14'}
This is more generic and reusable, I believe: 我相信这是更通用和可重用的:
import re
def tuple_producer(input_lines, attributes):
"""Extract specific attributes from lines 'blabla attribute=value …'"""
for line in input_lines:
line_attributes= {}
for match in re.finditer("(\w+)=(\d+)", line):
line_attributes[match.group(1)]= int(match.group(2)) # int cast
yield tuple(
line_attributes.get(attribute, 0) # int constant
for attribute in wanted_attributes)
>>> lines= """blablabla checked=12 unchecked=1
blablabla unchecked=13
blablabla checked=14""".split("\n")
>>> list(tuple_producer(lines, ("checked", "unchecked")))
[(12, 1), (0, 13), (14, 0)]
# and an irrelevant example
>>> list(tuple_producer(lines, ("checked", "inexistant")))
[(12, 0), (0, 0), (14, 0)]
Note the conversion to integer; 注意转换为整数; if it's undesirable, remove the
int
casting, and also convert the 0
int constant to "0"
. 如果它是不合需要的,删除
int
转换,并将0
int常量转换为"0"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.