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.