Perché Python la mostra ” ValueError: impossibile convertire la stringa di galleggiare?

Ho un file CSV contenente i numeri che sto cercando di convertire i carri allegorici.

filename = "filename.csv"
enclosed_folder = "path/to/Folder"
full_path = os.path.join(enclosed_folder,filename)

with open(full_path) as input_data:
    temp = input_data.readlines()
    n = len(temp) #int(temp.pop(0))
    matrix = [x.split(" ") for x in temp]
    for i in range(n):
        for j in range(n):
            matrix[i][j] = float(matrix[i][j])
    input_data.close()

Quando ho aperto il file in un editor di testo, non mostra il \n alla fine di ogni riga.

Perché Python la mostra

Ma l’esecuzione di codice python mostra il ValueError: impossibile convertire da stringa a galleggiare’ a causa di ‘\n’ essere presente alla fine di ogni riga.

Traceback (most recent call last):
  File "hierarchical-clustering.py", line 37, in <module>
    matrix[i][j] = float(matrix[i][j])
ValueError: could not convert string to float: '1,0.058824,0.076923,0.066667,0.055556,0.058824,0.071429,0.052632,0.076923,0.0625,0.0625,0.055556,0.055556,0.05,0.066667,0,0,0.055556,0.0625,0.058824,0.058824,0.047619,0.055556,0.0625,0,0.052632,0.066667,0.055556,0.0625,0.058824,0.041667,0.066667,0.058824,0.071429,0.066667,0.076923,0,0.083333,0.052632,0.071429,0.076923,0,0.0625,0.076923,0.058824,0.076923,0.055556,0,0.0625,0.071429,0.0625,0.0625,0.083333,0,0,0,0.058824,0.0625,0,0.058824,0.0625,0.0625,0.066667,0.0625,0.052632,0.066667,0.076923,0.058824,0.071429,0.066667,0.058824,0.071429,0.058824,0.071429,0.058824,0.071429,0.071429\n'

Così, come posso risolvere questo errore?

EDIT: ho usato strip() nonché rstrip() come suggerito in alcune risposte a rimuovere gli spazi bianchi, ma comunque l’errore non va via:

Traceback (most recent call last):
  File "hierarchical-clustering.py", line 37, in <module>
    matrix[i][j] = float(matrix[i][j].rstrip())
ValueError: could not convert string to float: '1,0.058824,0.076923,0.066667,0.055556,0.058824,0.071429,0.052632,0.076923,0.0625,0.0625,0.055556,0.055556,0.05,0.066667,0,0,0.055556,0.0625,0.058824,0.058824,0.047619,0.055556,0.0625,0,0.052632,0.066667,0.055556,0.0625,0.058824,0.041667,0.066667,0.058824,0.071429,0.066667,0.076923,0,0.083333,0.052632,0.071429,0.076923,0,0.0625,0.076923,0.058824,0.076923,0.055556,0,0.0625,0.071429,0.0625,0.0625,0.083333,0,0,0,0.058824,0.0625,0,0.058824,0.0625,0.0625,0.066667,0.0625,0.052632,0.066667,0.076923,0.058824,0.071429,0.066667,0.058824,0.071429,0.058824,0.071429,0.058824,0.071429,0.071429'
  • Non credo float se ne frega di punto e a capo. Ho appena provato float("1.0\n") sulla mia macchina e felicemente mi dà 1.0. Penso che il problema è il tuo virgole. float("1,2") non funziona, per esempio.
  • Avete pensato di utilizzare il csv modulo di leggere il file csv? Se l’uso che invece di cercare di analizzare il file manualmente, IIRC si esibiranno tipo rudimentale di conversione sul vostro conto. Quindi non c’è bisogno di chiamare float a tutti.
  • No, Python csv non si assume alcun tipo. Deliberatamente considera tutto una stringa. (Questo è più Divinatori (esplicito è meglio che implicita) ed evita una delle cose che i programmatori di odio di Excel).
  • Oops. Forse stavo pensando di terzi csv parser, quindi. Ancora, il modulo è utile anche senza fornire il tipo di conversione.
InformationsquelleAutor Kristada673 | 2017-06-29



3 Replies
  1. 6

    L’errore è dovuto alla tua linea di analisi. Si sono la separazione di spazi, non le virgole, che è quello che dovrebbe succedere secondo il tuo screenshot. La chiave sta visualizzando l’errore restituito. Si sta cercando di convertire l’intera linea da una stringa in un float.

    Modifica:

    matrix = [x.split(" ") for x in temp]

    A:

    matrix = [x.split(",") for x in temp]
    • Accidenti! Che stupido errore.
    • succede a tutti noi. La cosa migliore da fare è leggere i messaggi di errore molto attentamente per determinare la causa principale. In caso contrario, è probabile che per andare giù in un buco di coniglio e di sprecare un sacco di tempo prima di rendersi conto di quanto semplice sia stato l’errore commesso.
  2. 2

    è possibile utilizzare strip() per rimuovere gli spazi da una stringa.

    matrix[i][j] = float(matrix[i][j].strip())

    Se le virgole sono preoccupato, si potrebbe desiderare di .split(',') con la virgola e non con gli spazi:

    matrix = [x.strip().split(",") for x in temp]

Lascia un commento