我需要解析这样的一行:
foo, bar > 1.0, baz = 2.0
foo bar > 1.0 baz = 2.0
foo, bar, baz
foo bar baz
对于每个元素,它可以是$ string(> | <| <= |> = | =)$ num或只是$ string,分隔符','在元素之间是可选的。
在所有这些情况下,请将其识别为:
['foo', 'bar', 'baz']
我怎么能在python中做到这一点?
此代码还将检查语法:
import re
with open("input") as f:
for line in f:
line = line.strip()
# chop a line into expressions of the form: str [OP NUMBER]
exprs = re.split(r'(\w+\s*(?:[!<>=]=?\s*[\d.]*)?\s*,?\s*)', line)
for expr in exprs:
# chop each expression into tokens and get the str part
tokens = re.findall(r'(\w+)\s*(?:[!<>=]=?\s*[\d.]*)?,?', expr)
if tokens: print tokens
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句