我正在尝试在给定的文本中打印短语.我希望能够打印文本中的每个短语,从2个单词到文本长度允许的最大单词数.我在下面编写了一个程序,可以打印最多5个单词的短语,但我无法找到更优雅的方式来打印所有可能的短语.
我对短语的定义=字符串中的连续单词,无论含义如何.
def phrase_builder(i):
phrase_length = 4
phrase_list = []
for x in range(0, len(i)-phrase_length):
phrase_list.append(str(i[x]) + " " + str(i[x+1]))
phrase_list.append(str(i[x]) + " " + str(i[x+1]) + " " + str(i[x+2]))
phrase_list.append(str(i[x]) + " " + str(i[x+1]) + " " + str(i[x+2]) + " " + str(i[x+3]))
phrase_list.append(str(i[x]) + " " + str(i[x+1]) + " " + str(i[x+2]) + " " + str(i[x+3]) + " " + str(i[x+4]))
return phrase_list
text = "the big fat cat sits on the …
Run Code Online (Sandbox Code Playgroud) python ×1