Python:函数被调用一次后,如果我再次调用,它将打印0

2024-03-28 12:45:57 发布

您现在位置:Python中文网/ 问答频道 /正文

def data_mining (text_file, start, end):
    count = 0
    total_value = 0
    average = 0
    for file_line_number, line in enumerate(text_file):
        if (file_line_number % 2) == 0:
            value = line[start:end]
            value = int(value)
            total_value += value
            count += 1
    return total_value, count


def main ():
    #Main program.
    text_file = open("93cars.dat.txt", "r")

    city_mpg = data_mining(text_file, 52, 54)
    highway_mpg = data_mining(text_file, 55, 57)
    midrange_price = data_mining(text_file, 42, 44)

    print (city_mpg)
    print (highway_mpg)
    print (midrange_price)

main()  

我试图在文本中进行数据挖掘,但是在我调用一次数据挖掘函数之后,下次调用它时,它只返回0。我试图通过写入text_file2=text_file[:]来复制text_file,但它返回了一个错误。你知道吗


Tags: textnumberdatavaluemaindefcountline
2条回答

第一次调用data_mining()时,文件被读取,文件读取指针结束于文件末尾。在data_mining开头调用text_file.seek(0)将确保指针始终从文件开头开始。你知道吗

def data_mining (text_file, start, end):
    count = 0
    total_value = 0
    average = 0
    for file_line_number, line in enumerate(text_file):
        if (file_line_number % 2) == 0:
            value = line[start:end]
            value = int(value)
            total_value += value
            count += 1
    return total_value, count


def main ():
    #Main program.
    text_file = open("93cars.dat.txt", "r")
    city_mpg = data_mining(text_file, 52, 54)
    text_file.seek(0) #reset the file pointer to 0
    highway_mpg = data_mining(text_file, 55, 57)
    text_file.seek(0) #reset the file pointer to 0
    midrange_price = data_mining(text_file, 42, 44)

    print (city_mpg)
    print (highway_mpg)
    print (midrange_price)

main()  

基本上,您是在读取整个文件,而不是重置指针所在的位置。要么关闭文件,然后重新打开,这将花费更多的精力,要么使用参数0调用seek()函数。你知道吗

基本上,文件的read来源就像键入时文本文件中的光标。现在按住->键,直到到达文件末尾。下一次当您尝试读取某些内容时,如果您没有将光标设置回起始位置,它只会读取end of file符号并认为它是空的。你知道吗

seek(0)告诉文件指针或光标(在我们的示例中)返回到开始处。seek()获取一个以字节为单位的参数,以零作为开始。你知道吗

相关问题 更多 >