0

I have a file that has 'word'\t'num'\n as a string. I would like to convert it to a dictionary which I have done except how to a convert the value 'num' to a floating point number, so that the dict is of this format `{word : num} and the num is not a string but a floating point number.

Here is my script so far:

file_stream = open(infile)
file_list = file_stream.readlines()
dict_output = {}
for line in file_list:
    tmp = line.split()
    dict_output[tmp[0]] = float(tmp[1])

If I remove the float() the script runs fine and it creates a dictionary with the values as strings. When I try to cast the string as an int I get the error message: "ValueError: could not convert string to float: stand"

4

2 回答 2

3

您正在正确地将值转换为浮点数。

但是,您至少一行,其中 不仅仅是该行上的一个制表符,或者第二个值不是浮点数。尝试将您的代码更改为:

key, value = line.rsplit('\t', 1)
try:
    dict_output[key] = float(value)
except ValueError:
    print 'Unexpected line: {!r}'.format(line)

\t这会在最后一个制表符而不是任何空格上拆分行。这会使一行上可能有多个制表符的行保持不变,并假设只有最后一个值是浮点数。

如果这仍然失败,代码会打印出问题行,向我们展示我们可能需要修复的其他问题。

于 2013-05-05T15:20:10.923 回答
1

因为您的格式是:word'\t'num'\n所以 word 和 num 之间是t(制表符)。您应该从更改line.split()为 `line.split('\t')。所以,完整的代码应该是:

file_stream = open(infile)
file_list = file_stream.readlines()
dict_output = {}
for line in file_list:
    tmp = line.split('\t')
    dict_output[tmp[0]] = float(tmp[1])
于 2013-05-05T15:25:55.487 回答