Python reads floating-point numbers and reads text file Samples _python

Source: Internet
Author: User

Reading floating-point data from a text file is one of the most common tasks, and Python does not have scanf such input functions, but we can use regular expressions to extract floating-point numbers from a read string

Copy Code code as follows:

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 ()

File contents:

Copy Code code as follows:

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

Output results:

Copy Code code as follows:

12.540 56.00 1.2e2-1.2e2 3.0e-2 4e+3
[(' 12.540 ', '. 540 ', '), (' 56.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

Annotations:

Reads a text file by line, uses regular expressions to find floating-point numbers in a string, and uses the float () function to convert a string to a floating-point number

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.