我想从下面转换(使用python代码)
$a
至context('a')
#g
至intents('g').is_()
!#g
至intents('g').isNot_()
@c
至entities('c').any_()
@c:ge
至entities('c').is_('ge')
我做过的第一个,但是我没有找到正确的方法来做。 这就是我尝试的1:
import re
from itertools import groupby
class context:
grammar= r'and|or|#|\$|:|@|\w+'
def __init__(self, val):
self.val = val
def __repr__(self):
return "context('{}')".format(self.parse()[1])
def parse(self):
return re.findall(self.grammar, self.val)
c = context("$a") #Input
输出:
context('a') #1. $a To context('a')
答案 0 :(得分:0)
我不知道您要做什么,但要进行转换,我会使用re.sub()
import re
text = '$a AND #g OR !#g WITH @c BUT @c:ge AGAIN $start @hello:world BYE #end'
text = re.sub('\$(\w+)', r'content(\1)', text)
text = re.sub('!#(\w+)', r'intents(\1).isNot_()', text) # `!#g` has to be before `#g`
text = re.sub('#(\w+)', r'intents(\1).is_()', text)
text = re.sub('@(\w+):(\w+)', r'entities(\1).is_(\2)', text) # `@c:ge` has to be before `@c`
text = re.sub('@(\w+)', r'entities(\1).any_()', text)
print(text)
结果
content(a) AND intents(g).is_() OR intents(g).isNot_() WITH entities(c).any_() BUT entities(c).is_(ge) AGAIN content(start) entities(hello).is_(world) BYE intents(end).is_()
如果您要转换的文字比较复杂,则应显示有问题的文字
答案 1 :(得分:0)
这样的事情怎么样?
import re
class context:
grammar = r'and|or|#|\$|:|@|\w+'
subs = [
(r'\$(\w+)', "context('\\1')"),
(r'!#(\w+)', "intents('\\1').isNot_()"),
(r'#(\w+)', "intents('\\1').is_()"),
(r'@(\w+):(\w+)', "entities('\\1').is_('\\2')"),
(r'@(\w+)', "entities('\\1').any()")
]
def __init__(self, val):
self.val = val
def parse(self):
parsed = self.val
for sub in self.subs:
parsed = re.sub(*sub, parsed)
return parsed
>>> print(context('$foo\n#foo\n!#foo\n@foo\n@foo:bar').parse())
context('foo')
intents('foo').is_()
intents('foo').isNot_()
entities('foo').any()
entities('foo').is_('bar')