卡在python代码中,这让我感到困惑

时间:2019-11-29 21:05:34

标签: python python-3.x

我想从下面转换(使用python代码)

  1. $acontext('a')
  2. #gintents('g').is_()
  3. !#gintents('g').isNot_()
  4. @centities('c').any_()
  5. @c:geentities('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')

2 个答案:

答案 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')
相关问题