gpt4 book ai didi

python - 从列表中提取出发和到达

转载 作者:行者123 更新时间:2023-11-28 22:18:49 25 4
gpt4 key购买 nike

我正在尝试从结构和长度可变的列表中提取一些参数。基本上,这些参数是路线的出发地址和到达地址。此列表是根据自然语言中的一个句子构建的,因此它不遵循任何特定模板:

1st example : ['go', 'Buzenval', 'from', 'Chatelet']
2nd example : ['How', 'go', 'street', 'Saint', 'Augustin', 'from', 'Buzenval']
3rd example : ['go', 'from', '33', 'street', 'Republique', 'to', '12','street','Napoleon']

我已经设法为每种情况创建了另一个非常相似的列表,除了出发和到达被实际的词“出发”和“到达”代替。通过上面的例子,我得到:

1st example : ['go', 'arrival', 'from', 'departure']
2nd example : ['How', 'go', 'arrival', 'from', 'departure']
3rd example : ['go', 'from', 'departure', 'to', 'arrival']

现在我有了这两种列表,我想确定出发和到达:

1rst example : departure = ['Chatelet'], arrival = ['Buzenval']
2nd example : departure = ['Buzenval'], arrival = ['street','Saint','Augustin']
3rd example : departure = ['33','street','Republique'], arrival = ['12','street','Napoleon']

基本上,参数是两个列表中不同的所有内容,但我需要确定哪个是出发,哪个是到达。我认为 Regex 可以在这方面帮助我,但我不知道如何。

感谢您的帮助!

最佳答案

我找到了解决您的三个示例的方法。你应该改变的一件事是变量名,我不知道如何命名它们。 (这是旧版本,速度慢且难以理解。后面的版本更好)

def extract_places(names, modes):
keywords = set(modes).intersection(names)
extracted = [[] for _ in modes]
j = 0
for i, mode in enumerate(modes):
if mode.lower() in keywords:
if mode.lower() != names[j].lower():
while mode.lower() != names[j].lower():
extracted[i - 1].append(names[j])
j += 1
else:
extracted[i].append(names[j])
j += 1
else:
if names[j].lower() not in keywords:
while j < len(names) and names[j].lower() not in keywords:
extracted[i].append(names[j])
j += 1

extracted = dict(zip(modes, extracted))
return extracted["arrival"], extracted["departure"]

我找到了另一种方法,可能更容易理解。但这种方式比第一种方式快十倍,因此您可能想要使用它。

def partition(l, word): # Helper to split a list or tuple at an specific element
i = l.index(word)
return l[:i], l[i + 1:]

def extract_places(names, modes):
keywords = set(modes).intersection(names)
mapped = [(modes, names)]
for word in keywords:
new_mapped = []
for mode,name in mapped:
if word in mode:
m1, m2 = partition(mode, word)
n1, n2 = partition(name, word)
if m1:
new_mapped.append((m1, n1))
if m2:
new_mapped.append((m2, n2))
else:
new_mapped.append((mode,name))
mapped = new_mapped
mapped = {m[0]: n for m, n in mapped}
return mapped['arrival'], mapped['departure']

两种方式完全一样:

for example in ((['go', 'Buzenval', 'from', 'Chatelet'],
['go', 'arrival', 'from', 'departure']
),
(['How', 'go', 'street', 'Saint', 'Augustin', 'from', 'Buzenval'],
['How', 'go', 'arrival', 'from', 'departure']
),
(['go', 'from', '33', 'street', 'Republique', 'to', '12', 'street', 'Napoleon'],
['go', 'from', 'departure', 'to', 'arrival']
)):
print(extract_places(*example))

两者的打印:

(['Buzenval'], ['Chatelet'])
(['street', 'Saint', 'Augustin'], ['Buzenval'])
(['12', 'street', 'Napoleon'], ['33', 'street', 'Republique'])

关于python - 从列表中提取出发和到达,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50230160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com