一个Python程序,用于打印句子中相同长度的最长连续单词链



我的任务是编写一个Python脚本,该脚本将输出句子中相同长度的最长连续单词链。例如,如果输入是"To be or not To be",那么输出应该是"To, be, or"。

text = input("Enter text: ")
words = text.replace(",", " ").replace(".", " ").split()
x = 0
same = []
same.append(words[x])
for i in words:
if len(words[x]) == len(words[x+1]):
same.append(words[x+1])
x += 1
elif len(words[x]) != len(words[x+1]):
same = []
x += 1
else:
print("No consecutive words of the same length")
print(words)
print("Longest chain of words with similar length: ", same)

为了将字符串输入转换为单词列表并去掉任何标点符号,我使用了replace()和split()方法。这个列表的第一个单词将被附加到一个名为"same"的新列表中,该列表将包含具有相同长度的单词。然后,for循环将逐个比较单词的长度,如果长度匹配,则将它们附加到该列表中,如果不匹配,则清除列表。

if len(words[x]) == len(words[x+1]):
~~~~~^^^^^
IndexError: list index out of range

这是我一直遇到的问题,我就是不明白为什么索引超出了范围。

我将非常感谢任何帮助解决这个问题和修复程序。提前谢谢你。

使用groupby可以得到如下结果

from itertools import groupby
string = "To be or not to be"
sol = ', '.join(max([list(b) for a, b in groupby(string.split(), key=len)], key=len))
print(sol)
# 'To, be, or'

len()函数接受字符串作为参数,例如,在这段代码中,首先你必须转换words

谢谢!

最新更新