列表中n个列表的迭代循环和子

时间:2018-09-30 14:52:08

标签: python regex replace iterator zip

我希望这看起来不那么混乱。我有一个问题,我试图替换句子中的n个单词,并根据其词性对所有组合进行迭代。 即

  • 制作图片
  • 建立站点
  • 存货
  • 获取图片
  • 获取网站
  • 获取库存...

我不熟悉使用iterables并基于n个要替换的单词自动执行此循环,这让我挠头。以下是示例数据...

> replaceable_list: [('mow', 'VB'), ('lawn', 'NN')]

> mostCommon_list [['make', 'get', 'draw', 'sign', 'sell'], ['image', 'site', 'stock', 'drawing', 'photo', 'way', 'people', 'money', 'image', 'skill']]

> Question: "You are trying to earn one hundred nine dollars for some new CDs. If you charge forty-seven dollars to mow a lawn, how many lawns will you need to mow to earn the money?"

如您所见,我已经具有与replaceable_list对应的mostCommon_list。我一直在使用的最后一个代码如下:

:)

question = word_tokenize(question)
first_word = question
#This loops through each replacement word
mostCommonwords, mostCommonPOS = zip(*replaceable_list)
commonlisttuples = list(itertools.product(*mostCommon_list))
for wordsintuple in commonlisttuples:
    for wordintuple in wordsintuple:
        #print(wordintuple)
        for commonwords in mostCommonwords:
            print(replace_all(str(question), commonwords, wordintuple))

我太亲密了!更新:我已将上面的代码更改为:

    for x in result:
    print("x", x)
    for idxy, val in enumerate(replaceable_list): #Caputure the word and the POS in list
    #print("idxy", idxy, "\n", "val", val, "\n")
        print("replaceable_list",val[0]) #prints each replacement word
        print("mostCommon_list[idxy]",mostCommon_list[idxy], "\n") #prints the list that the replacement should come from 
        print(replace_all(str(first_word), val[0], x[idxy])) #target, find, replacement

这是我忘记提及的replace_all函数。抱歉。

  def replace_all (target,find,replace):
  return replace.join(target.split(find))

现在,我正在尝试将返回的结果加在一起。输入为割草,但输出如下:

  • 草坪
  • 修剪图片
  • 草坪
  • 修剪一个站点
  • 草坪
  • 修剪库存

而不是..

  • 制作一张图片
  • 建立一个站点
  • 制作库存
  • 获取一张图片
  • 获得一个网站
  • 获取 库存 ...

0 个答案:

没有答案