Reading floating point data from a text file is one of the most common tasks. python doesn't have an input function like scanf, but we can use regular expressions to extract floating point numbers from the read string
Copy Code The code is as follows.
import re
fp = open('c:/', 'r')
s = ()
print(s)
aList = ('([-+]?)'). \d+(\. \d*)? |\...\d+)([eE][-+]? \d+)([eE][-+]? \d+)?' ,s) #Search for strings using regular expressions
print(aList)
for ss in aList:
print(ss[0]+ss[2])
aNum = float((ss[0]+ss[2]))
print(aNum)
()
File contents:
Copy Code The code is as follows.
12.540 56.00 1.2e2 -1.2E2 3.0e-2 4e+3
Output results:
Copy Code The 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
Annotation:
Read in the text file line by line, use regular expression to find the floating point number in the string, use float() function to convert the string to floating point number