Python获取类型错误_io.BufferedRead

2024-09-29 23:23:11 发布

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

我正在尝试实现Prim算法,但是一直遇到这个错误,我不知道该怎么做。两个文件都是.txt文件,第一个文件(分配给matrizA的文件)包含邻接矩阵,而第二个文件是顶点名称列表,每行一个。在

import networkx as nx

def peso(matrizA, u,v):
    return matrizA[u][v]

def adjac(matrizA, u):
    L = []
    for x in range(len(matrizA)):
        L.insert(0,x)
    return L

def extraiMin(Q):
    q = Q[0]
    Q.remove(Q[0])
    return q

def decKey(Q, K):
    for i in range(len(Q)):
        for j in range(len(Q)):
            if K[Q[i]]< K[Q[j]]:
                s = Q[i]
                Q[i] = Q[j]
                Q[j] = s

def prim(vList, matrizA, r):
    u = 0
    v = 0
    P = [None]*len(vList)
    K = [999999999]*len(vList)

    Q=[0]*len(V)
    for u in range(len(Q)):
        Q[u] = vList[u]

    K[r] = 0
    decKey(Q, K)
    while len(Q) > 0:
        u = extraiMin(Q)   
        Adj = adjac(matrizA, u)
        for v in Adj:
            w = peso(matrizA, u)

            if Q.count(v) > 0 and w < K[v]:
                P[v] = u
                K[v] = w
                decKey(Q, K)
    return P

matrizA = open("C:\TrabalhoGrafos\Prim\MatrizAdjacencia_Pesos.txt", 'rb')
V = open("C:\TrabalhoGrafos\Prim\AirportList_Vertices.txt", 'rb')

P = prim(V, matrizA, 0)
print (P)

PyCharm向我展示的错误是:

Traceback (most recent call last):

File "C:/TrabalhoGrafos/Prim/Prim.py", line 74, in

P = prim(V, matrizA, 0)

File "C:/TrabalhoGrafos/Prim/Prim.py", line 40, in prim

P = [None]*len(vList)

TypeError: object of type '_io.BufferedReader' has no len()

我保留了其他功能


Tags: 文件intxtforlenreturndef错误
1条回答
网友
1楼 · 发布于 2024-09-29 23:23:11

您刚刚用V = open("C:\TrabalhoGrafos\Prim\AirportList_Vertices.txt", 'rb')打开了文件。
def prim(vList, matrizA, r)需要一个列表。
这是错误的,因为您将文件对象作为vList传递给prim()
文件对象没有名为len():https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects的方法

您应该将这些行作为一个列表来阅读,并将其传递给prim()
现在你刚打开文件,你还没读过里面的内容。在

你可以吃一些类似的东西:

vList_file = "C:\TrabalhoGrafos\Prim\AirportList_Vertices.txt"
with open(vList_file, "rt") as in_file:
    V = in_file.readlines()
V = [x.strip() for x in V]  # strip '\n' from each element
P = prim(V, matrizA, 0) 
...

小心,因为类似的情况适用于matrizA。在这种情况下,您还只是传递一个打开的file对象,这样当for x in range(len(matrizA)):def adjac(matrizA, u)中执行时,也会遇到类似的错误。在

还请记住,您有文本文件(看起来是这样的),因此您不应该以字节模式打开文件(即使用参数'rb')。
更多信息请访问
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

相关问题 更多 >

    热门问题