使用字典键捕获组的正则表达式

RegEx for capturing groups using dictionary key

我无法在我的字典函数中显示正确的命名捕获。我的程序读取一个 .txt 文件,然后将该文件中的文本转换为字典。我已经有了正确的正则表达式公式来捕获它们。

这是我的File.txt:

file Science/Chemistry/Quantum 444 1
file Marvel/CaptainAmerica 342 0
file DC/JusticeLeague/Superman 300 0
file Math 333 0
file Biology 224 1

这里是regex link可以捕捉到我想要的:

通过查看 link,我想要显示的那些以绿色和橙色突出显示。

我的这部分代码有效:

rx= re.compile(r'file (?P<path>.*?)( |\/.*?)? (?P<views>\d+).+')
i = sub_pattern.match(data) # 'data' is from the .txt file
x = (i.group(1), i.group(3))
print(x) 

但由于我正在将 .txt 制作成字典,所以我不知道如何制作 .group(1) 或 .group(3) 作为键来专门显示我的显示功能。我不知道如何在我使用 print("Title: %s | Number: %s" % (key[1], key[3])) 时显示这些组,它会显示那些内容。我希望有人能帮助我在我的字典功能中实现它。

这是我的词典功能:

def create_dict(data):
    dictionary = {}
    for line in data:
      line_pattern = re.findall(r'file (?P<path>.*?)( |\/.*?)? (?P<views>\d+).+', line)
      dictionary[line] = line_pattern
      content = dictionary[line]
      print(content)
    return dictionary

我试图让我的文本文件的输出看起来像这样:

Science 444
Marvel 342
DC 300
Math 333
Biology 224

This RegEx 可能会帮助您将输入分为四组,其中第 2 组和第 4 组是您可以简单提取的目标组,spaced 带有 space:

 (file\s)([A-Za-z]+(?=\/|\s))(.*)(\d{3})

您已经在 'line_pattern' 中使用了命名组,只需将它们放入您的字典即可。 re.findall 在这里不起作用。此外,'/' 之前的字符转义 '\' 是多余的。因此你的字典函数将是:

def create_dict(data):
    dictionary = {}
    for line in data:
        line_pattern = re.search(r'file (?P<path>.*?)( |/.*?)? (?P<views>\d+).+', line)
    dictionary[line_pattern.group('path')] = line_pattern.group('views')
    content = dictionary[line]
    print(content)
    return dictionary

您可以使用

用您的文件数据创建和填充字典
def create_dict(data):
    dictionary = {}
    for line in data:
        m = re.search(r'file\s+([^/\s]*)\D*(\d+)', line)
        if m:
            dictionary[m.group(1)] = m.group(2)
    return dictionary

基本上,它执行以下操作:

  • 定义一个 dictionary 字典
  • 逐行读取data
  • 搜索 file\s+([^/\s]*)\D*(\d+) 匹配项,如果有匹配项,则两个捕获组值用于形成字典键值对。

我建议的正则表达式是

file\s+([^/\s]*)\D*(\d+)

参见 Regulex graph 解释:

那么,你可以像这样使用它

res = {}
with open(filepath, 'r') as f:
    res = create_dict(f)
print(res)

参见Python demo