2013-05-01 55 views
2

所以我匹配(含实物捐助者的帮助下对堆栈溢出)的项目数:在使用变量REG-EX

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 

我不知道如果我能在后面的断言来看看使用变量.. 真的很感激我得到这里的帮助!

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

+1

在这里工作(CPython的2.6.2),您使用的是什么版本? 'python example.py Voyage' – AlessandroEmm 2013-05-01 09:09:20

+0

我有Python 2.7.2 ... – Siddhartha 2013-05-01 09:15:08

+1

检查你的输入。您的代码适用于我([Ideone示例](http://ideone.com/mD87Gp))。 – soon 2013-05-01 09:15:58

回答

1

在这里,一旦找到了数字,就可以使用'旧式'(如果需要,可以同样使用.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"]) 

Prodcuing

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

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

非常感谢Henry对我的两个问题的帮助。我虽然得到它的工作,只是不需要脱字符号。 – Siddhartha 2013-05-01 09:28:41

+1

确实的队友,乐于帮助。尽管出于兴趣,胡萝卜代表什么意思? – HennyH 2013-05-01 09:39:43

+0

我在第二个reg-ex中使用的“^”符号。 – Siddhartha 2013-05-01 09:41:38