python讀取浮點數和讀取文字檔樣本

來源:互聯網
上載者:User
從文字檔中讀入浮點數據,是最常見的任務之一,python沒有scanf這樣的輸入函數,但我們可以利用正規運算式從讀入的字串中提取出浮點數

複製代碼 代碼如下:


import re
fp = open('c:/1.txt', 'r')
s = fp.readline()
print(s)
aList = re.findall('([-+]?\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?',s) #使用正規運算式搜尋字串
print(aList)
for ss in aList:
print(ss[0]+ss[2])
aNum = float((ss[0]+ss[2]))
print(aNum)
fp.close()

檔案內容:
複製代碼 代碼如下:


12.540 56.00 1.2e2 -1.2E2 3.0e-2 4e+3

輸出結果:
複製代碼 代碼如下:


12.540 56.00 1.2e2 -1.2E2 3.0e-2 4e+3
[('12.540', '.540', ''), ('56.00', '.00', ''), ('1.2', '.2', 'e2'), ('-1.2', '.2', 'E2'), ('3.0', '.0', 'e-2'), ('4', '', 'e+3')]
12.540
12.54
56.00
56.0
1.2e2
120.0
-1.2E2
-120.0
3.0e-2
0.03
4e+3
4000.0

註解:

按行讀入文字檔,利用正規運算式找出字串中的浮點數,使用float()函數將字串轉換為浮點數

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.