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

这是能够捕获我想要的正则表达式链接:

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

我的这部分代码有效:

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
4

3 回答 3

2

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

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 图:

在此处输入图像描述

然后,您可以像这样使用它

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

请参阅Python 演示

于 2019-04-14T08:51:00.330 回答
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
于 2019-04-14T00:57:51.630 回答
0

此 RegEx可能会帮助您将输入分为四组,其中第 2 组和第 4 组是您的目标组,可以简单地提取它们并用 分隔space

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

在此处输入图像描述

于 2019-04-13T23:27:34.007 回答