<p>就我个人而言,我不认为我们需要为此使用任何其他模块(尽管我承认其中一些模块非常棒)。我只是通过简单的循环来管理这个问题,首先将字符串转换成一个列表。我在上面列出的所有例子上都试过了。它工作得很好。在</p>
<pre><code>sentence = str(raw_input("Please enter your sentence:\n"))
word_list = sentence.split()
def check_if_same(i,j): # checks if two sets of lists are the same
global word_list
next = (2*j)-i # this gets the end point for the second of the two lists to compare (it is essentially j + phrase_len)
is_same = False
if word_list[i:j] == word_list[j:next]:
is_same = True
# The line below is just for debugging. Prints lists we are comparing and whether it thinks they are equal or not
#print "Comparing: " + ' '.join(word_list[i:j]) + " " + ''.join(word_list[j:next]) + " " + str(answer)
return is_same
phrase_len = 1
while phrase_len <= int(len(word_list) / 2): # checks the sentence for different phrase lengths
curr_word_index=0
while curr_word_index < len(word_list): # checks all the words of the sentence for the specified phrase length
result = check_if_same(curr_word_index, curr_word_index + phrase_len) # checks similarity
if result == True:
del(word_list[curr_word_index : curr_word_index + phrase_len]) # deletes the repeated phrase
else:
curr_word_index += 1
phrase_len += 1
print "Answer: " + ' '.join(word_list)
</code></pre>