gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:58:55 27 4
gpt4 key购买 nike

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

最佳答案

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

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字典
  • 逐行读取数据
  • 搜索一个 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 .

关于python - 使用字典键捕获组的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55670677/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com