python - 将一个字典中的值与另一个字典中的键链接起来,并使用正则表达式在字符串中将一个替换为另一个

标签 python python-3.x regex dictionary regex-group

import re

def normalize_intervals_to_2_digits(match):
    input_text_substring = match.group()
    input_text_substring = re.sub(r"(\b\d)(?!\d)", r"0\1", input_text_substring, 2)
    return input_text_substring


#Examples:
input_text = "hay 4 objetos los 3 primeros dias del mes de enero del 2020"  #example 1
input_text = "hay que ir alli los 10 ultimos dias del mes de julio del 2022"  #example 2
input_text = "suelen ser algo frios los primeros dias del mes de noviembre"  #example 3
input_text = "hay que plantar 5 calabazas los ultimos dias del mes de octubre del 2021"  #example 4


#month data dictionaries
es_month_dict = {"enero": "01", "febrero": "02", "marzo": "03", "abril": "04", "mayo": "05", "junio": "06", "julio": "07", "agosto": "08", "septiembre": "09", "octubre": "10", "noviembre": "11", "diciembre": "12"}
quantity_days_associated_to_month_num = { "01":"01_to_31", "02":"01_to_28", "03":"01_to_31", "04":"01_to_30", "05":"01_to_31", "06":"01_to_30", "07":"1_to_31", "08":"01_to_31", "09":"01_to_30", "10":"01_to_31", "11":"01_to_30", "12":"01_to_31" }

last_day_of_this_month = .replace("01_to_","") #for example, "01_to_31" --> "31"

#here do the day's replacements...
input_text_substring = re.sub( , , input_text)


input_text_substring = re.sub(r"\(\d{1,2} -- \d{1,2}\)", normalize_intervals_to_2_digits, input_text)

print(repr(input_text)) #output

Day的字符串根据所属月份的转换规则:

n 作为通用数字 \d{1,2} :

"los primeros n dias"---> (01 -- 0n)

"los ultimos n dias"---> (last_day_of_this_month - n -- last_day_of_this_month)

或者考虑 5 作为标准,如果没有明确指出数字,那么我们将假设 n = 5 天:

"los primeros dias"---> (01 -- 05)

"los ultimos dias"---> (last_day_of_this_month - 5 -- last_day_of_this_month)

正确的输出应该是这些:

"hay 4 objetos los (01 -- 03) del mes de enero del 2020"  #for the example 1
"hay que ir alli los (20 -- 30) del mes de julio del 2022"  #for the example 2, 30 - 10 = 20
"suelen ser algo frios los (01 -- 05) del mes de noviembre"  #for the example 3
"hay que plantar 5 calabazas (26 -- 31) del mes de octubre del 2021"  #for the example 4, 31 - 5 = 26

如何将字典 es_month_dict 中的数据与字典 quantity_days_associated_to_month_num 中的日期链接起来,以设置输入字符串中的替换逻辑?

最佳答案

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import re
from datetime import datetime
from calendar import monthrange

def getRange(m):
    # default 5 days
    days  = m.group(1)
    if days == None:
        days = 5
    else:
        days = int(days)

    # month text to int
    month = m.group(3).lower()
    month = monthToInt(month)

    # default year todays year
    year  = m.group(5)
    if year == None:
        year = datetime.now().strftime('%Y')

    # first and last day by type
    type  = m.group(2)
    if type == 'primeros':
        first_day = 1
        last_day = first_day + days
    elif type == 'ultimos':
        last_day = int(getLastDayFromMonth(month, year))
        first_day = last_day - days

    first_day = setMaskToNumber(first_day, 2)
    last_day = setMaskToNumber(last_day, 2)

    result = first_day+" -- "+last_day

    return result

def setMaskToNumber(number, mask):
    result = str(number)
    while(len(result)<mask):
        result = "0"+result
    return result

def monthToInt(month):
    es_month_dict = {"enero": 1, "febrero": 2, "marzo": 3, "abril": 4, "mayo": 5, "junio": 6, "julio": 7, "agosto": 8, "septiembre": 9, "octubre": 10, "noviembre": 11, "diciembre": 12}
    month = es_month_dict.get(month)
    return month

def getLastDayFromMonth(month, year):
    r = monthrange(int(year), int(month))
    return r[1]

#Examples:
#input_text = "hay 4 objetos los 3 primeros dias del mes de enero del 2020"  #example 1
input_text = "hay que ir alli los 10 ultimos dias del mes de julio del 2022"  #example 2
#input_text = "suelen ser algo frios los primeros dias del mes de noviembre"  #example 3
#input_text = "hay que plantar 5 calabazas los ultimos dias del mes de octubre del 2021"  #example 4

"""
"hay 4 objetos los (01 -- 03) del mes de enero del 2020"  #for the example 1
"hay que ir alli los (20 -- 30) del mes de julio del 2022"  #for the example 2, 30 - 10 = 20
"suelen ser algo frios los (01 -- 05) del mes de noviembre"  #for the example 3
"hay que plantar 5 calabazas (26 -- 31) del mes de octubre del 2021"  #for the example 4, 31 - 5 = 26
"""

m = re.search(r'([0-9]+\s)?(primeros|ultimos) dias del mes de (\w+)( del ([0-9]+))?', input_text)

if m:
    range = getRange(m)
    output = re.sub(r'([0-9]+\s*)?(primeros|ultimos) dias', range, input_text)
    print(output)

我将月份 dict 更改为 int,如果年份没有出现在我使用此时此刻的年份的句子中。

关于python - 将一个字典中的值与另一个字典中的键链接起来,并使用正则表达式在字符串中将一个替换为另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73958401/

相关文章:

python - 用空格分隔符打破列表值 - Python

python - 如何从 Python 列表中删除偶数?

python - 如何在 Python 中表示 'Enum'?

python - 在 IPython 中控制列表可视化

REGEX:从字符串中提取路径

python - 值错误: endog and exog matrices are different sizes - how to drop data in specific columns only?

python - 按每行中的列数对 csv 进行排序

javascript - 使用 javascript 和正则表达式获取查询字符串

regex - Vim - 如何在所有缓冲区中运行非正常模式命令?

python - 如何在亚马逊网络服务中从 boto3 生成 url