简体   繁体   English

如何在Python中动态生成此代码?

[英]How to generate this code dynamically in Python?

I have a large list of data and another list of patterns. 我有大量的数据列表和另一个模式列表。 I'm trying to filter data using the patterns. 我正在尝试使用模式过滤数据。 Here's my code using some sample data: 这是使用一些示例数据的代码:

dataList = [ '4334 marked val 5656 bin', 
    '76-67-34 done this 99', 
    'bin ket AZZ3R434 pid' 
]

for data in dataList:
    regexList = [ re.search(r'val ([\d]+) bin', data),
            re.search(r'bin ket ([A-Z\d-]+)\b', data)
        ]

    for reg in regexList:
        if reg:                   #If there's a match
            #...do something...
            break

In the above code in regexlist the 're.search()' part is getting repeated again and again. 在上面的正则表达式代码中,“ re.search()”部分一次又一次地重复。 I want to keep only a list of patterns, something like below: 我只想保留模式列表,如下所示:

regexList = [ 'val ([\d]+) bin',
        'bin ket ([A-Z\d-]+)\b'
    ]

And use these patterns one by one with re.search() later. 并在稍后与re.search()一一对应使用这些模式。 I tried using eval() and exec() both, but just kept getting errors. 我尝试同时使用eval()和exec(),但是一直出错。

I would also like to know whether 'regexList' is getting created again and again under for loop? 我也想知道是否在for循环下一次又一次创建了“ regexList”?

I don't see why you would need to do this with eval/exec. 我不明白为什么您需要使用eval / exec来执行此操作。 Just pass the pattern to re.search inside the loop: 只需将模式传递给循环内的re.search即可:

regexList = [
    r'val ([\d]+) bin',
    r'bin ket ([A-Z\d-]+)\b'
]
for pattern in regexList:
    if re.search(pattern, data):
        ...
dataList = [ '4334 marked val 5656 bin', 
    '76-67-34 done this 99', 
    'bin ket AZZ3R434 pid' 
]

regexList = [
         r'val ([\d]+) bin',
         r'bin ket ([A-Z\d-]+'
]
for data in dataList:
    for reg in regexList:
        if  re.search(reg,data):                   #If there's a match
            #...do something...
            break

i would suggest use a "router" (for example Dromeo , i'm author), the point is that a router matches patterns and executes actions if pattern matches, so it is what you need exactly. 我建议使用“路由器”(例如Dromeo ,我是作者),重点是路由器匹配模式并在模式匹配时执行操作,因此这正是您所需要的。

Example: 例:

import Dromeo

router = Dromeo()

router.on('4334 marked val {%INT%:val} bin', my_handler)

router.route('4334 marked val 5656 bin')

def my_handler( params ):
   # val is already typecasted to integer
   print(params['data']['val'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM