繁体   English   中英

Python根据接收到的输入动态创建一个字符串修改的lambda函数

[英]Pythonically creating a string-modifying lambda function dynamically based off of input recieved

我有一个Web表单,它接受用户输入以进行字符串修改,以应用于通过CSV中给定列传递的信息。 因为我试图使用现有的体系结构,所以我将这些修改应用于lambda函数。 对于大多数mod来说,这是相当简单的,但是对于我的replace修改,我想动态地执行此操作,例如,我可能从表单中收到的字符串可能是:

(“您”,“我” /“ this”,“ that” /“ do”,“ do n't”)

我想为传递此数据而创建的等效lambda为:

func = lambda v: str(v).replace('you', 'me').replace('this', 'that').replace('do', "don't")

我可以通过限制可替换的数量,然后计算定界符(在这种情况下为'/'),然后使用if语句等单独创建定界符,轻松地做到这一点。
我讨厌这个想法有两个原因:

  1. 通过限制允许在给定字符串上进行多少次修改,我有效地限制了用户的修改能力
  2. 它感觉不像pythonic。

我更喜欢这样的方法:

func = lambda v: str(v)
for mod in modstring.split(' / '):
    func = func + .replace(mod.split(', ')[0], mod.split(', ')[1])

但是我非常怀疑这种功能是否存在...我认为这个问题是一个长期的尝试,但是值得一试。

lambda和常规函数可以互换。 因此,我会将其写为返回函数的函数:

def make_replacer(s):
    mods = [mod.split(', ') for mod in s.split(' / ')]
    def replacer(v):
        v = str(v)
        for mod in mods:
            v = v.replace(mod[0], mod[1])
        return v
    return replacer

使用示例:

>>> f1 = make_replacer('foo, bar / moo, car')
>>> f2 = make_replacer('foo, dar / moo, ear')
>>> f1('foo$$moo')
'bar$$car'
>>> f2('foo$$moo')
'dar$$ear'
import re

# I am going to assume that your form input is literally of the form
# """('you', 'me' / 'this', 'that' / 'do', "don't")"""
# so this parses it into
# [("you", "me"), ("this", "that"), ("do", "don't")]
def parse_form_string(s, reg=re.compile("(['\"])(.*?)(\\1)")):
    words = [qw[1] for qw in reg.findall(s)]
    return zip(words[::2], words[1::2])

# we use the input-string to build a function
# which will perform the replacements
def my_replace_fn(form_string):
    pairs = parse_form_string(form_string)
    def fn(s):
        for a,b in pairs:
            s = s.replace(a, b)
        return s
    return fn

# then we can use it like
inp = """("cat", 'dog' / "mouse", "flea" )"""
my_fn = my_replace_fn(inp)

my_fn("my cat has a mouse")   # => "my dog has a flea"

考虑一下:

parse_replace = lambda i: i.split(', ') # 'one, two' => [ 'one', 'two' ]

f = lambda v, inputstring: reduce( lambda a,b: a.replace(*parse_replace(b)), v.split(' / '), inputstring )

# So: f('one, derp / three, four', 'onetwothree') # ==> 'derptwofour'

注意:这假设您输入的字符串的格式实际上是:“一,二/三,四”。

暂无
暂无

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

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