连接有重叠词的输入句子



任务是将重叠的输入句子连接起来。我的问题是如何正确地去除重叠的部分。

输入:第一行是要连接的句子数。下一行是句子。输出:连接句

例子:

输入:

2
The harder you work for something, the
something, the greater you?ll feel when you achieve it.

输出:

The harder you work for something, the greater you?ll feel when you achieve it.

我代码:

def connect(sentence1,sentence2):
x= None
y= None
for i in range(len(sentence2)):
if sentence2[:len(sentence2)-i] in sentence1 and len(sentence2[:len(sentence2)-i]) != 1:
y =(sentence1+' '+sentence2[len(sentence2)-i:].strip())
x =True
break
return x,y
n = int(input())
lst = []
for i in range(n):
a = input()
lst.append(a)
for i in lst:
for j in lst:
if i ==j:
pass
elif True in connect(i,j):
lst.remove(i)
lst.remove(j)
lst.append(connect(i,j)[1])
print(lst[0])

输入1:

3
The fool doth think he is wise,
wise man knows himself to be a fool.
wise, but the wise

输出1:错误

The fool doth think he is wise, man knows himself to be a fool. but the wise

期望输出1:

The fool doth think he is wise, but the wise man knows himself to be a fool.

输入2:

7
afraid of greatness.
Be not afraid
some achieve greatness,
greatness thrust upon them.
greatness. Some
Some are born great, some
greatness, and others have greatness
输出2:error
line 21, in 
lst.remove(i)
ValueError: list.remove(x): x not in list

期望输出2:

Be not afraid of greatness. Some are born great, some achieve greatness, and others have greatness thrust upon them.

您需要跟踪重叠的长度(end-start或start-end),以便从您连接的其中一个部分中剪切适当数量的字符:

sentences = """afraid of greatness.
Be not afraid
some achieve greatness,
greatness thrust upon them.
greatness. Some
Some are born great, some
greatness, and others have greatness""".split("n")
result = sentences.pop(0) # start with any part, and take it out
while sentences:
for s in list(sentences):
atEnd   = next((p for p in range(1,len(s)) if result[-p:]==s[:p]),0)
if atEnd:                        # length of overlapping end-start
result = result + s[atEnd:]  # append to end, cut starting overlap
sentences.remove(s)
continue
atStart = next((p for p in range(1,len(s)) if result[:p]==s[-p:]),0)
if atStart:                      # length of overlapping start-end
result = s[:-atStart]+result # insert at start, cut ending overlap
sentences.remove(s)
print(result)
Be not afraid of greatness. Some are born great, some achieve greatness, and others have greatness thrust upon them.

相关内容

  • 没有找到相关文章

最新更新