【问题标题】:python string replacement, all possible combinations #2python字符串替换,所有可能的组合#2
【发布时间】:2015-07-19 14:01:53
【问题描述】:

我有这样的句子:

((wouldyou)) give me something ((please))

还有一堆关键字,存储在数组/列表中:

keywords["wouldyou"] = ["can you", "would you", "please"]
keywords["please"] = ["please", "ASAP"]

我想用存储在数组中的一组合适的字符串替换括号中出现的每个变量,并返回所有可能的组合。变量和关键字的数量未定义。

James helped me 使用以下代码:

def filler(word, from_char, to_char):    
    options = [(c,) if c != from_char else (from_char, to_char) for c in word.split(" ")] 
    return (' '.join(o) for o in product(*options)) 
    list(filler('((?please)) tell me something ((?please))', '((?please))', ''))

它很好用,但只会用空字符串替换一个特定的变量。现在我想用不同的关键字来处理各种变量。期望的结果应该是这样的:

can you give me something please
would you give me something please
please give me something please
can you give me something ASAP
would you give me something ASAP
please give me something ASAP

我猜这与to_ch有关,但我不知道如何通过这个地方的列表项进行比较。

【问题讨论】:

    标签: python string replace iteration combinations


    【解决方案1】:

    以下将起作用。它使用itertools.product 构建关键字的所有可能配对(或更多配对)。

    import re, itertools
    
    text = "((wouldyou)) give me something ((please))"
    
    keywords = {}
    keywords["wouldyou"] = ["can you", "would you", "please"]
    keywords["please"] = ["please", "ASAP"]
    
    # Get a list of bracketed terms
    lsources = re.findall("\(\((.*?)\)\)", text)
    
    # Build a list of the possible substitutions 
    ldests = []
    for source in lsources:
        ldests.append(keywords[source])
    
    # Generate the various pairings
    for lproduct in itertools.product(*ldests):
        output = text
        for src, dest in itertools.izip(lsources, lproduct):
            # Replace each term (you could optimise this using a single re.sub)
            output = output.replace("((%s))" % src, dest)
    
        print output
    

    您可以通过避免使用一个re.sub() 调用进行多次replace() 和赋值调用来进一步改进它。

    此脚本提供以下输出:

    can you give me something please
    can you give me something ASAP
    would you give me something please
    would you give me something ASAP
    please give me something please
    please give me something ASAP
    

    它使用 Python 2.7 进行了测试。如果使用了多个相同的关键字,您将需要考虑如何解决它。希望你觉得这很有用。

    【讨论】:

    • 非常感谢先生。这太不可思议了,让我了解了 itertools 的工作原理。我一定会解决您提到的问题并报告我的进展。
    【解决方案2】:

    这是 Regex 队长的工作!

    部分,伪代码,解决方案......

    一个直接的,尽管效率低下(如 O(n*m),其中 n 是要替换的单词数,m 是每个单词的平均替换数),这样做的方法是使用 re 模块中的正则表达式功能匹配单词,然后使用 re.sub() 方法将它们换出。然后你可以将它嵌入到嵌套循环中。所以(假设你先把你的替代品放入一个 dict 或其他东西中),它看起来像这样:

    for key in repldict:
      regexpattern = # construct a pattern on the fly for key
      for item in repldict[key]:
        newstring = re.sub(regexpattern, item)
    

    等等。只有,你知道,就像正确的语法和东西一样。然后只需将新字符串附加到列表中,或者打印它,或者其他什么。

    为了动态创建正则表达式,字符串连接就应该这样做。就像匹配左括号的正则表达式,加上要匹配的字符串,再加上匹配右括号的正则表达式。

    如果你这样做,那么你可以通过循环第二个版本的正则表达式模式来处理可选功能,该模式在左括号的末尾附加一个问号,然后做任何你想做的事情.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 2021-12-15
      • 1970-01-01
      • 2020-08-18
      • 2017-11-11
      相关资源
      最近更新 更多