Python example of Reading Floating Point Numbers and reading text files

Source: Internet
Author: User

Reading Floating Point data from a text file is one of the most common tasks. python does not have an input function like scanf, but we can use regular expressions to extract floating point data from the read string.

Copy codeThe Code is as follows:
Import re
Fp = open ('C:/1.txt ', 'R ')
S = fp. readline ()
Print (s)
AList = re. findall ('([-+]? \ D + (\. \ d *)? | \. \ D +) ([eE] [-+]? \ D + )? ', S) # use regular expressions to search strings
Print (aList)
For ss in aList:
Print (ss [0] + ss [2])
ANum = float (ss [0] + ss [2])
Print (aNum)
Fp. close ()

File Content:
Copy codeThe Code is as follows:
12.540 56.00 1.2e2-1.2E2 3.0e-2 4e + 3

Output result:
Copy codeThe Code is as follows:
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

Note:

Read text files by line, use regular expressions to find floating point numbers in a string, and use the float () function to convert the string to a floating point number.

Related Article

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.