Python正则表达式从句子中提取地址和旅行时间?
我正在使用正则表达式解析句子中的地址和时间。不同的句子变量是:Python正则表达式从句子中提取地址和旅行时间?,python,regex,Python,Regex,我正在使用正则表达式解析句子中的地址和时间。不同的句子变量是: 我想从宇宙站到绿巷公路525号 我想明天早上8点从宇宙站去格林兰公路525号 我想在早上8点从宇宙站到绿巷525公路 我希望用一种简单的方法来解决这个问题,得到一个介于from和to之间的文本,并假设它是一个原点,等等 from(.*)to(*.) 走这条路对吗?我正在寻找提取来源,目的地和时间。预期的结果是: Origin = cosmos station Destination = 525 Greenlane Highway
from(.*)to(*.)
走这条路对吗?我正在寻找提取来源,目的地和时间。预期的结果是:
Origin = cosmos station
Destination = 525 Greenlane Highway
remaining_string = none if sentences ends at destination
remaining_string = text after destination
from\s(?P[\d\w\s]*?)\sto\s(?P[\d\w\s]*?)(?:$|(?P\b(?:明天在)\b.*))
你可以看看我的解决方案
有三个命名的捕获组,每个捕获组对应一个目标变量
您会注意到,在时间捕获组中,我有(明天|在)
,用于匹配时间子字符串的时间起始词
虽然这适用于您的特定问题,但必须对所有其他可能检查的时间值进行扩展
如果我们不知道我们可以或不能做出什么样的假设,那么很难创建一个能够捕获所有边缘情况的正则表达式,所以请随意发布完整的预期输入集 这项工作适用于给定的样本:
import re
string = """
I want to go from Cosmos Station to 525 Greenlane highway.
I want to go from Cosmos Station to 525 Greenlane highway tomorrow at 8am.
I want to go from Cosmos Station to 525 Greenlane highway at 8am
"""
# to make the pattern a little readable
# in your example time separator are either at or tomorrow at you can add more
at_separators = {'at': '(?:(?:tomorrow at)|(?:at))'}
# after to we capture all string if there is no at separator after it
# if there is second group will capture the string between too and at separator
pattern = 'from\s(.+?)\sto\s(.+?(?=\s{at})|.+(?!{at}\s))(?:\s{at}(.+))?'.format(**at_separators)
pattern = re.compile(pattern, flags=re.MULTILINE)
# no you hust need to clean the result to clean '.' and noises because doing this
# in the pattern will make it a unreadable.
print(re.findall(pattern, string))
输出:
[('Cosmos Station', '525 Greenlane highway.', ''), ('Cosmos Station', '525 Greenlane highway', ' 8am.'), ('Cosmos Station', '525 Greenlane highway', ' 8am')]
正如您在第一组中看到的,第三个位置是空字符串,因为没有时间。键为正向前瞻
+?(?=\s{at})
开关不会消耗时间部分,但它将通过(?:\s{at}(+)?
返回 (*)
肯定是错误的。这里的问题是您需要定义一些要应用的规则。例如,525绿巷公路
似乎是第二个示例中的目的地。您如何区分目的地和时间?请在(.*)尝试从(.*)到(.*)的?也许您可以硬编码“明天”和其他可能出现在“at”之前的特殊单词,但一般来说,这对于正则表达式来说太难了,您需要某种实体检测/语义解析/…请指定您的预期输出。添加了预期输出
[('Cosmos Station', '525 Greenlane highway.', ''), ('Cosmos Station', '525 Greenlane highway', ' 8am.'), ('Cosmos Station', '525 Greenlane highway', ' 8am')]