簡體   English   中英

字符串'-1'無法轉換為float

[英]string '-1' can't be converted to float

我嘗試從使用utf-8編碼打開的文本文件中讀取大量數字。 文本文件是來自pdf的復制/粘貼。 問題在於負數(-1,-2等):我剝離了所有內容,因此單個字符串位看起來像這樣: -1-2等。

然后我想用它們計算並用float()轉換它們,但是我得到一個錯誤:

can't convert string to float: '-1'

我得出結論, '-'可以被解釋為一個長'-' ,無論調用什么,並在文本文件中用'-'手動替換它。 現在它適用於這個單字符串,float()轉換它。 我寫了一個小腳本,在文本文件中查找並替換所有'-''-' ,但是沒有用。

with open('text.txt', encoding='utf8') as fobj:
    all = []
    for line in fobj:
        line = line.strip()
        if '-' in line:
            line.replace('-','-')
            print('replaced')
        all.append(line)
with open('text2.txt','w',encoding='utf8') as f:
    for i in all:
        print(i)
        f.write(i)
        f.write('\n')

為什么我可以手動將'-'替換為'-'而不是用這個腳本替換? 感謝幫助。

從文本文件中剪切的示例:

/ 11/3 / 2 / 0 / 0/–1 /
/ 11/5 / 0 / 2 / 0/0 / N
/ 12/3 / 1 / 0 / 0/0 /
/ 12/4 / 1 / 1 / 0/0 / NS

/ 12/4 / 4 / –1 / 0/–1 / H

/ 12/5 / 1 / 0 / 0/–1 / H

/ 12/5 / 2 / 0 / 0/-1 / H

/ 11/4 / 0 / 0 / 0/0 / H

您實際上可以看到倒數第二行和第三行之間的差異-1。 在這個副本中。 我替換了最后一個 - 手動。

你錯過了分配line

if '-' in line:
    line = line.replace('-','-')
    print('replaced') 

我只看了你的代碼:它確實replace('-','-') - 這是相同的字符。

您應該replace('–','-') ,或者為了更清楚地了解您的操作,請replace(u'\–', '-')

此外,您的重新分配line丟失了。

使用兩個答案你的代碼應該是:

with open('text.txt', encoding='utf8') as fobj:
        all_ = []
        for line in fobj:
            line = line.strip()
            if u'\u2013' in line:
                line = line.replace(u'\u2013', '-')
                print('replaced', line)
            all_.append(line)
    with open('text2.txt','w',encoding='utf8') as f:
        for i in all_:
            print(i)
            f.write(i)
            f.write('\n')

結果是

replaced / 11/3 / 2 / 0 / 0/-1 /
replaced / 12/4 / 4 / -1 / 0/-1 / H
replaced / 12/5 / 1 / 0 / 0/-1 / H
/ 11/3 / 2 / 0 / 0/-1 /
/ 11/5 / 0 / 2 / 0/0 / N
/ 12/3 / 1 / 0 / 0/0 /
/ 12/4 / 1 / 1 / 0/0 / NS

/ 12/4 / 4 / -1 / 0/-1 / H

/ 12/5 / 1 / 0 / 0/-1 / H

/ 12/5 / 2 / 0 / 0/-1 / H

/ 11/4 / 0 / 0 / 0/0 / H

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM