【发布时间】:2022-12-24 22:38:22
【问题描述】:
我有以下格式的字典列表:
ldict = [
{'start_offset': 0, 'end_offset': 10, 'string_type': 'verb'},
{'start_offset': 5, 'end_offset': 15, 'string_type': 'noun'},
{'start_offset': 20, 'end_offset': 30, 'string_type': 'noun'},
{'start_offset': 42, 'end_offset': 51, 'string_type': 'adj'},
{'start_offset': 45, 'end_offset': 52, 'string_type': 'noun'}
]
start_offset和end_offset表示字符串中子串的开始和结束位置。
我的目标是将重叠的字符串组合在一起以仅形成一行。
start_offset 将是最低位置,end_offset 将是最高位置。
输出示例:
ldict = [
{'start_offset': 0, 'end_offset': 15, 'string_type': ['verb', 'noun']},
{'start_offset': 20, 'end_offset': 30, 'string_type': ['noun']},
{'start_offset': 42, 'end_offset': 52, 'string_type': ['adj', 'noun']}
]
我的尝试:
import pandas as pd
final = []
for row in ldict:
i1 = pd.Interval(row['start_offset'], row['end_offset'])
semi_fin_list = []
for one_row in ldict:
i2 = pd.Interval(one_row['start_offset'], one_row['end_offset'])
if i1.overlaps(i2):
semi_fin_list.append(once)
final.append(semi_fin_list)
在上面的尝试中,我可以得到一行的重叠,但被困在下一步我可以做什么来排序和组合行以保持不同的行。
我怎样才能达到同样的效果?我的尝试还没有得出结论,因为我仍然得到重复。
【问题讨论】:
-
遍历列表,比较字典中的偏移量和组重叠。
-
我卡住了。我确实尝试了一个嵌套的 for 循环,其中一行与所有其他行进行比较,但我得到了重复的行,不知道如何对它们进行排序。
-
@nifeco,请将您的代码添加到问题中。
-
@martineau 我只是在寻求帮助,你不需要无礼。我没有添加我的代码,因为我觉得它是错误的,而且可能有更好的我不知道的方法。
-
@OlvinRoght 编写尝试的代码需要时间,因为我正在无法复制粘贴的远程桌面上编写代码。
标签: python python-3.x