【问题标题】:Got stuck in python code which made me confused卡在python代码中,这让我感到困惑
【发布时间】:2019-11-29 21:05:34
【问题描述】:

我想从下面转换(使用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')

【问题讨论】:

  • 第一个代码中有什么?用什么语言?
  • 第一个代码不是代码。这是我想要转换的 5 种格式。我试图解决第一点@furas
  • 你不能使用普通的replace("$a", "context('a')") 吗?或者它们意味着更多?
  • 不!我想有适当和稳定的方式。 @furas 请查看我尝试过的上面的代码...
  • 也许您应该使用if/else 来分别处理每个规则。

标签: python python-3.x


【解决方案1】:

这样的事情怎么样?

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')

【讨论】:

  • 让我检查一下,我会回复你。 @Seb
【解决方案2】:

我不知道你想做什么,但要转换它我会使用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_()

如果您有更复杂的文本要转换,那么您应该在问题中显示它

【讨论】:

  • 我想是的...让我检查一下@furas。
猜你喜欢
  • 2012-10-05
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多