【发布时间】:2021-10-27 14:57:43
【问题描述】:
我有一个多词列表,例如:
['President Barack', 'Barack Obama', 'New York', 'York City', 'United States', 'States of America', 'This is not overlapping']
我想合并重叠的多字以获得这样的东西:
['President Barack Obama', 'New York City', 'United States of America', 'This is not overlapping']
我已经尝试过取自另一个类似问题的代码:
strFrag = ['President Barack', 'Barack Obama', 'New York', 'York City', 'United States', 'States of America', 'This is not overlapping']
for repeat in range(0, len(strFrag)-1):
bestMatch = [2, '', ''] #overlap score (minimum value 3), otherStr index, assembled str portion
for otherStr in strFrag[1:]:
for x in range(0,len(otherStr)):
if otherStr[x:] == strFrag[0][:len(otherStr[x:])]:
if len(otherStr)-x > bestMatch[0]:
bestMatch = [len(otherStr)-x, strFrag.index(otherStr), otherStr[:x]+strFrag[0]]
if otherStr[:-x] == strFrag[0][-len(otherStr[x:]):]:
if x > bestMatch[0]:
bestMatch = [x, strFrag.index(otherStr), strFrag[0]+otherStr[-x:]]
if bestMatch[0] > 2:
strFrag[0] = bestMatch[2]
strFrag = strFrag[:bestMatch[1]]+strFrag[bestMatch[1]+1:]
但它只适用于列表的第一个单词,给我这个结果:
['President Barack Obama', 'New York', 'York City', 'United States', 'States of America', 'This is not overlapping']
我的问题是:你将如何解决它?
感谢您的宝贵时间!
编辑:我希望只有接近的词被合并,所以如果我有 ['President Barack', 'Some word', 'Other word', 'Barack Obama'],Barack Obama 总统不会合并。
更新:也许这样的事情是正确的,但如果可能的话,我想听听你的意见
strFrag = ['President Barack', 'Barack Obama', 'Obama of the USA', 'New York', 'York City', 'Test', 'Hello how', 'how you doin?']
for i in range(len(strFrag)):
strFrag[i] = strFrag[i].split()
for i in range(len(strFrag)-1,-1,-1):
if (strFrag[i][0] == strFrag[i-1][-1]):
strFrag[i-1].remove(strFrag[i-1][-1])
strFrag[i] = strFrag[i-1] + strFrag[i]
strFrag.remove(strFrag[i-1])
for i in range(len(strFrag)):
strFrag[i] = ' '.join(strFrag[i])
它给了我:
['President Barack Obama of the USA',
'New York City',
'Test',
'Hello how you doin?']
【问题讨论】:
-
您想将每个短语与开头重叠最多的另一个短语连接起来吗?如果一个结尾短语可以连接到两个不同的起始短语 - 你可以分别加入两个短语还是只加入其中一个短语?如果是后者,结尾短语应该连接到哪个开头——列表中的第一个还是重叠最多的那个?你能加入多个短语的链——双重和三重重叠等吗?
-
我只想加入彼此靠近的短语,因为在我的数据集中我有很长的短语列表,否则会导致问题。如果可能的话,我还想要多个连锁店(例如:(美国总统乔·拜登)将是“美国总统乔·拜登”,但前提是它们在附近)。