Python regexp中的语法错误

时间:2013-11-11 17:57:23

标签: python syntax-error

当我开始编写一个函数时,我收到了语法错误。我在REPL尝试了执行行 - 这很有效。但我想在IDE上做这件事。有人可以帮帮我吗?

我的代码:

def sentence_splitter(file_name):
    with open(file_name) as f:
        input_str = f.read()
        period_indexes = get_periods(input_str)
        for el in period_indexes:
            sub_str = input_str[el - 14:el + 14]
            if not re.search(r'\.\s+[A-Za-z]{1,3}\w+', sub_str) and # Error here
            re.search(r'\.\d+', sub_str) and
            re.search(r'\.\s+[a-z]+', sub_str) and
            re.search(r'([A-Za-z\.]+\.\w+){1,50}', sub_str) and
            re.search(r'\w+\.[\.,]+', s):
                pass

3 个答案:

答案 0 :(得分:3)

你的if语句需要括号:

def sentence_splitter(file_name):
    with open(file_name) as f:
        input_str = f.read()
        period_indexes = get_periods(input_str)
        for el in period_indexes:
            sub_str = input_str[el - 14:el + 14]
            if not (re.search(r'\.\s+[A-Za-z]{1,3}\w+', sub_str) and # Error here
            re.search(r'\.\d+', sub_str) and
            re.search(r'\.\s+[a-z]+', sub_str) and
            re.search(r'([A-Za-z\.]+\.\w+){1,50}', sub_str) and
            re.search(r'\w+\.[\.,]+', s)):
                pass

技术上反斜杠可行,但括号更Pythonic,请参阅PEP8:http://www.python.org/dev/peps/pep-0008/#maximum-line-length

答案 1 :(得分:2)

您的条件跨越多行。您需要添加续行符\

if not re.search(r'\.\s+[A-Za-z]{1,3}\w+', sub_str) and \
            re.search(r'\.\d+', sub_str) and \
            re.search(r'\.\s+[a-z]+', sub_str) and \
            re.search(r'([A-Za-z\.]+\.\w+){1,50}', sub_str) and \
            re.search(r'\w+\.[\.,]+', s):

有关此问题的更多信息,请参见PEP8和此answer

特定于您的代码的一条注释:

re.search(r'\w+\.[\.,]+', s)
                          ^---- This variable is not assigned 
                                (likely should be sub_str)

答案 2 :(得分:1)

在你的上一个正则表达式中:

re.search(r'\w+\.[\.,]+', s)

您对未定义的s执行搜索。所有其他正则表达式都在substr上执行搜索,这可能就是您想要的。这会提高NameError,而不是SyntaxError

此外,您可能希望重构代码以使其更易于阅读,正如我对您的问题的评论中所述。

相关问题