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