如何更正此列表映射功能?

How can I correct this list mapping function?

我正在尝试制作一个 python 函数,该函数接受一个 excel 公式的字符串并将其更改为伪可读文本,反之亦然根据此映射。

mapping = {"'2020 Projects'!$I3" : "end_date",
"'2020 Projects'!$H3" : "start_date",
"'2020 Projects'!$L3" : "perc_baa",
"'2020 Projects'!$G3" : "prob",
"'2020 Projects'!$J3" : "monthly_rev",
"43951": "april_30_number",
"43922": "april_1_number",
"43952": "may_1_number",}

现在我有这个但结果不正确。

def code_to_ex(s):
    excel = s
    for word, code in mapping.items():
        excel = s.replace(code, word)
        print(excel)

def ex_to_code(s):
    code = s
    for word, code in mapping.items():
        code = s.replace(code, word)
        print(code)

这是一个示例输入和输出:

String ="IF('2020 Projects'!$H3>43922,yes,no)"

ex_to_code(String)
answer -> IF(start_date>apr1, yes no)

String2 = 'IF(start_date>apr30, no, yes)'
code_to_ex(String2)
answer -> 'IF(2020 Projects'!$H3>43951,no,yes)'

您的代码存在一些问题。我希望我没有遗漏任何内容,但如果有任何不清楚的地方,请告诉我:

mapping = {"'2020 Projects'!$I3" : "end_date",
"'2020 Projects'!$H3" : "start_date",
"'2020 Projects'!$L3" : "perc_baa",
"'2020 Projects'!$G3" : "prob",
"'2020 Projects'!$J3" : "monthly_rev",
"43951": "april_30_number",
"43922": "april_1_number",
"43952": "may_1_number",}

def code_to_ex(s):
    excel = s
    for word, code in mapping.items():
        # not excel = s.replace, since you want to continuously update excel
        excel = excel.replace(code, word)
    print(excel)

def ex_to_code(s):
    # renamed code to all_code, since you are iterating over mapping.items() with code
    all_code = s
    for word, code in mapping.items():
        # same issue as above
        all_code = all_code.replace(word, code)
    print(all_code)

String1 = "IF('2020 Projects'!$H3>43922,yes,no)"
String2 = 'IF(start_date>april_30_number, no, yes)'

ex_to_code(String1)
code_to_ex(String2)

输出:

IF(start_date>april_1_number,yes,no)
IF('2020 Projects'!$H3>43951, no, yes)

一个警告,因为这个方法有点天真:如果 codeword 的子串,你可能会被绊倒,反之亦然,因为映射可能是执行两次:例如对于规则 {'AB': 'C', 'C': 'D'},字符串 AB 可能映射到 D.

变量excel每次更新。

因此,您应该按如下方式更改函数。

def code_to_ex(s):
    for word, code in mapping.items():
        s = s.replace(code, word)
    print(s)

def ex_to_code(s):
    for word, code in mapping.items():
        s = s.replace(code, word)
    print(s)