繁体   English   中英

docstring阻止elif语句

[英]docstring blocks elif statement

让我过去我拥有的确切代码:这是简短的模块

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

文档字符串只是在函数开始处找到的字符串文字。 他们仍然必须遵守缩进规则。

您的字符串未正确插入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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM