我无法在我的字典函数中显示正确的命名捕获。我的程序读取一个 .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

