我正在使用正则表达式将文件中的数字移动到列表中,然后添加所有数字。我在理解我需要放入值括号中以使这些数字成为浮点数时遇到问题。
import re
fhand = open('regex_sum_42.txt')
numlist = list()
for line in fhand:
line = line.rstrip()
value = re.findall('([0-9.]+)', line)
num = float(value()) # Need to know what to put in the value () .
numlist.append(num)
print value
答案 0 :(得分:0)
这里存在两个问题......
1:要将值转换为float,您必须迭代它将其转换为float或简单地将其映射到值列表。
2:你的浮点数和int数的正则表达式并不完美...
import re
fhand = open('regex_sum_42.txt')
numlist = list()
for line in fhand:
line = line.rstrip()
value = re.findall(r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?', line)
num = [float(i[0]) for i in value] # this is simply fetch first element from list of tuples and convert in into float
print value