gpt4 book ai didi

python - 在正则表达式中使用变量

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:00 24 4
gpt4 key购买 nike

所以我匹配(在堆栈溢出贡献者的帮助下)项目编号:

User Number 1 will probably like movie ID: RecommendedItem[item:557, value:7.32173]the most!

现在我正尝试使用项目编号从另一个文本文件中提取相应的名称。它的内容如下:

557::Voyage to the Bottom of the Sea (1961)::Adventure|Sci-Fi

出于某种原因,我只是想在终端上显示“无”。未找到匹配项。

myfile = open('result.txt', 'r')
myfile2 = open('movies.txt', 'r')
content = myfile2.read()
for line in myfile:
m = re.search(r'(?<=RecommendedItem\[item:)(\d+)',line)
n = re.search(r'(?<=^'+m.group(0)+'\:\:)(\w+)',content)
print n

我不确定我是否可以在回溯断言中使用变量..非常感谢我在这里获得的所有帮助!

编辑:原来唯一的问题是第二个正则表达式中不需要的插入符号。

最佳答案

在这里,一旦找到数字,就可以使用“旧式”(如果需要,同样可以使用 .format)字符串格式将其放入正则表达式中。我认为通过字典访问值会很好,因此命名匹配,但你可以在没有这个的情况下做到这一点。要获取流派列表,只需.split("|") suggestionDict["Genres"] 下的字符串即可。

import re
num = 557
suggestion="557::Voyage to the Bottom of the Sea (1961)::Adventure|Sci-Fi"

suggestionDict = re.search(r'%d::(?P<Title>[a-zA-Z0-9 ]+)\s\((?P<Date>\d+)\)::(?P<Genres>[a-zA-Z1-9|]+)' % num, suggestion).groupdict()
#printing to show if it works/doesn't
print('\n'.join(["%s:%s" % (k,d) for k,d in suggestionDict.items()]))
#clearer example of how to use
print("\nCLEAR EXAMPLE:")
print(suggestionDict["Title"])

制作

Title:Voyage to the Bottom of the Sea 
Genres:Adventure|Sci
Date:1961

CLEAR EXAMPLE:
Voyage to the Bottom of the Sea
>>>

关于python - 在正则表达式中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16315383/

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