MST

星途 面试题库

面试题:Python利用findall和finditer处理复杂文本查找位置

有一段复杂文本,其中包含多种格式的日期,格式如 'YYYY - MM - DD'、'MM/DD/YYYY' 和 'DD - Mon - YYYY',请使用Python的re模块,利用findall和finditer方法,找出所有日期在文本中的位置,并将日期及其位置整理成字典形式输出。假设文本为:'The meeting is on 2023 - 10 - 15. Another event is set for 11/20/2024. And there is one more on 18 - Oct - 2025'。请写出完整代码实现。
21.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import re

text = 'The meeting is on 2023 - 10 - 15. Another event is set for 11/20/2024. And there is one more on 18 - Oct - 2025'

pattern = re.compile(r'(\d{4}-\d{2}-\d{2}|\d{2}/\d{2}/\d{4}|\d{2}-[a-zA-Z]{3}-\d{4})')

result_dict = {}
for match in pattern.finditer(text):
    result_dict[match.group()] = match.span()

print(result_dict)
import re

text = 'The meeting is on 2023 - 10 - 15. Another event is set for 11/20/2024. And there is one more on 18 - Oct - 2025'

matches = re.findall(r'(\d{4}-\d{2}-\d{2}|\d{2}/\d{2}/\d{4}|\d{2}-[a-zA-Z]{3}-\d{4})', text)
result_dict = {match: (text.index(match), text.index(match) + len(match)) for match in matches}

print(result_dict)