python中针对不同对的匹配键

2024-09-29 23:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

由于属性的名称不同,我需要将键值的键与正则表达式进行匹配。你知道吗

可能的名称在dict中定义:

MyAttr  = [
    ('ref_nr', 'Reference|Referenz|Referenz-Nr|Referenznummer'),
    ('color', 'Color|color|tinta|farbe|Farbe'),
]

从另一个dict中的项导入属性:

ImportAttr  = [
    ('Referenz', 'Ref-Val'),
    ('color', 'red'),
]

现在我想返回import属性的值,如果它是一个已知的属性(在我的第一个dict MyAttr中定义)匹配有问题的属性的不同拼写。你知道吗

for key, value in ImportAttr:
    if key == "Referenz-Nr" : ref      = value
    if key == "Farbe"       : color    = value

目标是返回可能属性的值(如果该属性是已知的)。你知道吗

print(ref)
print(color)

如果“referez Nr”和“Farbe”是已知属性,则应返回值。你知道吗

很明显,这个伪代码不起作用,我只是无法理解一个实现regex的函数来进行键搜索。你知道吗


Tags: key名称refif属性定义valuenr
2条回答

我不清楚,但也许你想要:

#!/usr/bin/python3

MyAttr  = [
    ('ref_nr', 'Reference|Referenz|Referenz-Nr|Referenznummer'),
    ('color', 'Color|color|tinta|farbe|Farbe')
]

ImportAttr  = [
    ('Referenz', 'Ref-Val'),
    ('color', 'red'),
]

ref, color = None, None

for key, value in ImportAttr:
    if key in MyAttr[0][1].split('|'): 
        ref = value
    if key in MyAttr[1][1].split('|'): 
        color = value

print("ref: ", ref)
print("color: ", color)

拆分可以通过分隔符(“|”字符)将字符串拆分为一个字符串列表,然后可以检查该列表中是否有键。你知道吗

下面的解决方案有点棘手。如果不想将位置硬编码到源代码中,可以使用locals()。你知道吗

#!/usr/bin/python3

MyAttr  = [
    ('ref', 'Reference|Referenz|Referenz-Nr|Referenznummer'),
    ('color', 'Color|color|tinta|farbe|Farbe')
]

ImportAttr  = [
    ('Referenz', 'Ref-Val'),
    ('color', 'red'),
]

ref, color = None, None

for var, names in MyAttr:
    for key, value in ImportAttr:
        if key in names.split('|'):
            locals()[var] = value
            break

print("ref: ", ref)
print("color: ", color)

如果需要,还可以使用pandas以这种方式解决大型数据集的这个问题。你知道吗

get_references_and_colors.py
import pandas as pd
import re
import json

def get_references_and_colors(lookups, attrs):
    responses = []

    refs = pd.Series(re.split(r"\|", lookups[0][0]))
    colors = pd.Series(re.split(r"\|", lookups[1][0]))
    d = {"ref": refs, "color": colors}
    df = pd.DataFrame(d).fillna('') # To drop NaN entries, in case if refs 
                                    # & colors are not of same length 

    #               ref  color
    # 0       Reference  Color
    # 1        Referenz  color
    # 2     Referenz-Nr  tinta
    # 3  Referenznummer  farbe
    # 4                  Farbe

    for key, value in attrs:
        response = {}
        response["for_attr"] = key

        df2 = df.loc[df["ref"] == key]; # find in 'ref' column

        if not df2.empty:
            response["ref"] = value
        else:
            df3 = df.loc[df["color"] == key]; # find in 'color' column
            if not df3.empty:
                response["color"] = value
            else:
                response["color"] = None # Not Available
                response["ref"] = None

        responses.append(response)

    return responses


if __name__ == "__main__":

    LOOKUPS  = [
         ('Reference|Referenz|Referenz-Nr|Referenznummer', 'a'),
         ('Color|color|tinta|farbe|Farbe', 'b'),
    ]

    ATTR  = [
        ('Referenz', 'Ref-Val'),
        ('color', 'red'),
        ('color2', 'orange'), # improper
        ('tinta', 'Tinta-col')
    ]

    responses = get_references_and_colors(LOOKUPS, ATTR) # dictionary
    pretty_response = json.dumps(responses, indent=4) # for pretty printing
    print(pretty_response)
Output
[
    {
        "for_attr": "Referenz",
        "ref": "Ref-Val"
    },
    {
        "for_attr": "color",
        "color": "red"
    },
    {
        "for_attr": "color2",
        "color": null,
        "ref": null
    },
    {
        "for_attr": "tinta",
        "color": "Tinta-col"
    }
]

相关问题 更多 >

    热门问题