我正在尝试使用 “ python get_timestamp.py -f gsham_input.xvg -1 -0.1348 -2 -0.1109” 运行以下python 。但是,似乎python错误地将小数点前的减号加了破折号,并显示了以下错误:“ file” get_timestamp.py“,第21行,在value1 = float(arg)ValueError中:float()的无效文字:−0.1348“您能帮助我知道如何解决吗?
谢谢。
#!/usr/bin/env python """ Given two values, looks in a 3 column-file (output of sham.pl) which time frame matches closest. """ import sys USAGE = "USAGE: get_timestamp.py -f <sham output> -1 <value 1> -2 <value 2>\n" # Parse arguments read_input, read_value1, read_value2 = False, False, False input_file, value1, value2 = None, None, None for arg in sys.argv[1:]: if read_input: read_input = False input_file = arg elif read_value1: read_value1 = False value1 = float(arg) elif read_value2: read_value2 = False value2 = float(arg) if arg[0] == "-": if arg == "-f": read_input = True continue elif arg == "-1": read_value1 = True continue elif arg == "-2": read_value2 = True else: print USAGE sys.stderr.write('ERROR: Option not recognized: %s\n' %arg) sys.exit(1) if not input_file: print USAGE sys.stderr.write('ERROR: You forgot to provide an input file.\n') sys.exit(1) # Open sham output x_values, y_values, time_values = [], [], [] fhandle = open(input_file) for line in fhandle: if line[0] != "#" and len(line.split()) == 3: t,x,y = line.split() x_values.append(float(x)) y_values.append(float(y)) time_values.append(float(t)) fhandle.close() def find_common_frame(min_x, min_y): for xval in min_x: xframe = xval[0] for yval in min_y: yframe = yval[0] if xframe == yframe: return (xframe, xval[1], yval[1]) return (None, None, None) # If you cannot find anything, try increasing the nval variable nval = 50 min_x = sorted(enumerate(x_values), key=lambda x: abs(x[1]-value1))[:nval] min_y = sorted(enumerate(y_values), key=lambda x: abs(x[1]-value2))[:nval] frame, x, y = find_common_frame(min_x, min_y) if not frame: print "No timestamp found.." sys.exit(0) print "## T = %s (%s, %s)" %(time_values[frame], x, y)
这不是Python问题,您传递的浮点数以减号(−,unicode U + 2212)开头,而不是常规的连字符-减号(-unicode U + 002D,Python和大多数语言使用的符号为“减号”标志)。我猜这是因为您从某个文档中复制了数字,因为很难用键盘键入Unicode减号。
−
-
一种简单的解决方案是,当您在命令行中调用程序时,用常规的连字符替换这些符号。如果您 确实 需要编程来处理这些符号,则可以使用如下函数来解析数字,而不是调用float:
float
def float_unicode(arg_str): return float(arg_str.decode("utf8").replace(u"\u2212", "-"))
但是,我不建议这样做,因为它会使程序更加复杂,并且大多数使用数字的命令行工具都不支持此功能,因此用户通常不希望您的程序这样做。