正则表达式类型定义

时间:2018-12-05 15:03:05

标签: regex string python-3.x

如何使用正则表达式将字符串分成令牌并调用所需令牌的函数。 例如:

Привет -> ru_word_func ()
SPACE -> space_func ()
world -> en_word_func ()
! -> pnct_func ()

1 个答案:

答案 0 :(得分:0)

像这样吗?

callr

输出:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import re

input = """
Привет SPACE world !
"""

d = {
    "Привет": "ru_word_func",
    "SPACE": "space_func",
    "world": "en_word_func",
    "!": "pnct_func"
}

def ru_word_func():
    print("ru_word_func")

def space_func():
    print("space_func")

def en_word_func():
    print("en_word_func")

def pnct_func():
    print("pnct_func")


g = re.findall(r"[^\s]+", input, re.MULTILINE)

for i in g:
    if i in d:
#       print(d[i])
        a = d[i]
        globals()[a]()