我希望这看起来不那么混乱。我有一个问题,我试图替换句子中的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))
现在,我正在尝试将返回的结果加在一起。输入为割草,但输出如下:
而不是..