1

我即将完成我的第一个合并排序程序,并且在编译时遇到了麻烦。我已经对这个特定错误进行了大量研究,似乎我在代码中的某个地方并不具体。我仍然找不到所说的错误,并希望得到您的帮助。我附上了文件内容、代码和回溯。再次感谢。

文件:

999 Message C1 
1033 Message C2 
1054 Message C3 
1056 Message C4 
1086 Message C5

代码:

DEBUG = True
out = []

logs = open("C:\Users\----\Desktop\logs.txt", mode ="r")

lines = logs.readline()

def debug(s):
    if DEBUG:
        print "DEBUG: ", s

def get_t (line):
    s = line
    s = s.lstrip()
    debug(s)
    i = s.find(" ")
    debug(s)
    s = s[:i]
    return int(s)

def get_lowest_i(logs):
    lowest_i = -1
    for i in range(len(logs)):
        log = logs[i]
        debug("log=" + repr(log))
        if log:
            t = get_t(log[0])
            debug("t=" + repr(t))
            if lowest_i == -1 or t < lowest_t:
                lowest_i = i
                lowest_t = t
    return lowest_i

def get_line_lowest_t(logs):
    while True:
        i = get_lowest_i(logs)
        if i == -1:
            break
        line = logs[i].pop(0)

def mergesort(logs):
    while True:
        line = get_line_lowest_t(logs)
        if line == None:
            break
        out.append(line)
    return out

print mergesort(logs)

f.close()

追溯:

Traceback (most recent call last):
  File "<module1>", line 50, in <module>
  File "<module1>", line 44, in mergesort
  File "<module1>", line 37, in get_line_lowest_t
  File "<module1>", line 24, in get_lowest_i
TypeError: object of type 'file' has no len()

提前致谢。

4

3 回答 3

1

TypeError: object of type 'file' has no len()该错误说明了您正在尝试读取文件对象的长度...作为logs = open("C:\Users\----\Desktop\logs.txt", mode ="r")一个文件,您的意思可能是读取文件的行并对其进行排序...lines = longs.readlines() print mergesort(lines)

于 2012-06-25T20:12:36.193 回答
1

文件没有方法 len()。将其放入字符串或数组中,然后使用 len()

于 2012-06-25T20:16:48.040 回答
0

您正在对文件进行合并排序,而不是对名为lines.

于 2012-06-25T20:11:43.120 回答