python - 用于if语句

时间:2010-07-27 20:31:54

标签: python jira

我不明白为什么,当我运行我的代码时,if语句下的每个循环都没有运行。即使找到的数量大于0!

def findpattern(commit_msg):
    pattern = re.compile("\w\w*-\d\d*")
    group = pattern.finditer(commit_msg)
    found = getIterLength(group)
    print found
    if found > 0:
        issues = 0
        for match in group:
                print " print matched issues:"
                auth = soap.login(jirauser,passwd)

                print match.group(0)
                getIssue(auth,match.group(0))
                issues = issues + 1
    else: 
        sys.exit("No issue patterns found.")

print "Retrieved issues: " + str(issues)  

任何帮助都会受到赞赏,我一直在敲打这个问题一小时。

2 个答案:

答案 0 :(得分:8)

您的getIterLength()函数通过耗尽finditer()返回的迭代器来查找长度。然后,您需要for循环的新迭代器实例。相反,我会像这样重构您的代码:

def findpattern(commit_msg):
    pattern = re.compile("\w\w*-\d\d*")
    group = pattern.finditer(commit_msg)

    found = 0
    issues = 0
    for match in group:
        print " print matched issues:"
        auth = soap.login(jirauser,passwd)

        print match.group(0)
        getIssue(auth,match.group(0))
        issues = issues + 1
        found += 1
    if found == 0:
        sys.exit("No issue patterns found.")


    print "Retrieved issues: " + str(issues)  

或者,您可以使用findall()方法而不是finditer()来为您提供一个列表(可以迭代,而不是迭代器),您可以在其上运行len(group)来获取大小,然后使用它在你的for循环中迭代。

答案 1 :(得分:1)

检查你的代码格式化它看起来像你有一个双标签而不是一个标签,记得python非常挑剔缩进