RegEx使用字典键捕获组

问题描述 投票:3回答:3

我在字典函数中显示正确的命名捕获时遇到问题。我的程序读取.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

通过查看链接,我想要显示的链接以绿色和橙色突出显示。

这部分代码有效:

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
python regex dictionary
3个回答
1
投票

您可以使用您的文件数据创建和填充字典

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解释它:

enter image description here

然后,你可以像使用它一样

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

Python demo


1
投票

您已经在'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

0
投票

This RegEx可能会帮助您将输入划分为四组,其中组2和组4是您的目标组,可以简单地提取并用空格隔开:

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.