这段代码有什么问题?

时间:2013-05-14 00:23:28

标签: python

应该为变量分配某些行号,然后将其分配给全局变量,然后打印出来。

bookStartLine = None
bookEndLine   = None


def grabLine(currentUrl): 

    ### blah blah defines what lines is
    index=0
    for line in lines:
        index+=1
        if "*** START OF THE PROJECT" in line:
            currentBookStartLine = index
        if "*** END OF THE PROJECT" in line:
            currentBookEndLine = index


    global bookStartLine
    global bookEndLine

    bookStartLine = currentBookStartLine
    bookEndLine   = currentBookEndLine


grabline('http://www.gutenberg.org/cache/epub/768/pg768.txt') 

print(bookStartLine)
print(bookEndLine)

2 个答案:

答案 0 :(得分:0)

尝试

global bookStartLine
global bookEndLine


def grabLine(currentUrl):
    ### blah blah defines what lines is
    currentBookStartLine,currentBookEndLine = False,False #needed to define these before use below
    for index,line in enumerate(lines,start=1): #start = 1 so index gets 1 on first iteration
        if "*** START OF THE PROJECT" in line:
            currentBookStartLine = index
        if "*** END OF THE PROJECT" in line:
            currentBookEndLine = index

    bookStartLine = currentBookStartLine
    bookEndLine   = currentBookEndLine


grabLine('http://www.gutenberg.org/cache/epub/768/pg768.txt') #grabLine not grabline

print(bookStartLine)
print(bookEndLine)

答案 1 :(得分:0)

这段代码很糟糕:

import urllib.request

bookName      = None
authorName    = None
bookStartLine = None
bookEndLine   = None


def parser(currentUrl): #parses texts to extract their title, author, begginning line and end line
    global bookName
    global authorName
    global bookStartLine
    global bookEndLine
    global url

    url = 'http://www.gutenberg.org/cache/epub/1232/pg1232.txt' #machiaveli
    url = currentUrl    
    book = urllib.request.urlopen(url)
    lines = book.readlines()
    book.close()

    finalLines = [line.decode()[:-2] for line in lines]


    for line in finalLines:
        if "Title" in line:
            currentBookName = line[7:len(line)]
            break
    for line in finalLines:
        if "Author" in line:
            currentAuthorName = line[8:len(line)]
            break
    currentBookStartLine,currentBookEndLine = False,False

    for index,line in enumerate(line,start=1):
        if "*** START OF THE PROJECT" in line:
            currentBookStartLine = index

        if "*** END OF THE PROJECT" in line:
            currentBookEndLine = index



    url           = currentUrl
    bookName      = currentBookName
    authorName    = currentAuthorName
    bookStartLine = currentBookStartLine
    bookEndLine   = currentBookEndLine


parser('http://www.gutenberg.org/cache/epub/768/pg768.txt') #wuthering heights
print(url)
print(bookName)
print(authorName)
print(bookStartLine)
print(bookEndLine)