2013-08-31 101 views
0

让我过去确切的代码我有: 这是短模块文档字符串块的elif声明

class SentenceSplitter: 

def __init__(self, filename=None): 
    self._raw_text = self.raw_text(filename) 
    self._sentences = self.to_sentences() 


def raw_text(self, filename): 
    text = '' 
    with open(filename, 'r') as file: 
     for line in file.readlines(): 
      line = line.strip() 
      text += ''.join(line.replace(line, line+' ')) 
    file.close() 
    text = text.strip() # Deal with the last whitespace 
    return text 

def to_sentences(self): 
    """ Sentence boundaries occur at '.', '!', '?' except that, 
    there are some not-sentence boundaries that 
    may occur before/after the period. 
    """ 
    raw_text = self._raw_text 
    sentences = [] 
    sentence = '' 
    boundary = None 

    for char in raw_text: 
     sentence += ''.join(char) 
     if char == '!' or char == '?': 
      sentences.append(sentence) 
      sentence = '' 

     """ The sign -> refers to 'followed by' """ 
     elif char == '.': 
      i = raw_text.index(char) # slicing previous/following characters 
      boundary = True 

     if boundary: 
      sentences.append(sentence) 
      sentence = '' 

    return sentences 

和主:

import textchange 

ss = textchange.SentenceSplitter(filename='text.txt') 
print(ss._sentences) 

第一if语句

后的文档字符串
""" The sign -> refers to 'followed by' """ 

我评论出来,程序运行,否则不会。 elif语句中有更多的代码,但在确定它仍然抛出错误之后将其删除。这里是回溯:

Traceback (most recent call last): 
File "D:\Programs\Python 3.3.2\Tutorials\46 Simple Python Exercises.py", line 26, in   
<module> 
import textchange 
File "D:\Programs\Python 3.3.2\Tutorials\textchange.py", line 51 
elif char == '.': 
^
SyntaxError: invalid syntax 

回答

5

文档字符串是在功能的开始发现只是字符串文字。他们仍然必须遵守缩进规则。

您的字符串未正确缩进elif块;通过从之前的if区块中删除,您完全结束了if - elif-else区块,并且没有elif允许后面。

改为使用常规的普通注释,以#开头的行;包含注释行被免除从缩进规则:

if char == '!' or char == '?': 
    sentences.append(sentence) 
    sentence = '' 

# The sign -> refers to 'followed by' 
elif char == '.': 
    i = raw_text.index(char) # slicing previous/following characters 
    boundary = True 

或缩进的字符串(其全部仍然被Python执行作为代码,但在其他未分配并因此再次丢弃):

if char == '!' or char == '?': 
    sentences.append(sentence) 
    sentence = '' 

elif char == '.': 
    """ The sign -> refers to 'followed by' """ 
    i = raw_text.index(char) # slicing previous/following characters 
    boundary = True