Python: 如何从文本文件中提取浮点值?

Python: How to extract float values from text file?

我在这样的文件中有内容,我只想从中提取浮点值。文本文件也包含新行,也应在 Python.

中将其删除
hub,0.0166
cord,0.0166
ever,0.0332
switch,0.0498
sleep,0.06639
allow,0.09959

work,0.14939

我试过这个:

newDict = list()
for words in file:
    splitline = words.split()
    newDict.append("{0}\t{1}".format(splitline[0],log(float(splitline[1]))))
    newDict[float(splitline[0])] = ",".join(splitline[1:])
print(newDict)

我观察到的错误是:

Traceback (most recent call last):
  File "G:\Setups\Python\chi-1.py", line 11, in <module>
    newDict.append("{0}\t{1}".format(splitline[0],log(float(splitline[1]))))
IndexError: list index out of range

但我没有得到任何输出 它向我显示了错误。如果有人知道如何只提取浮点数,则循环中的变量文件包含文本 file.So。请帮忙解决。

提前致谢

你可以使用csv模块来简化它:

from math import log

l = []

with open('path/to/file', 'r') as f:
    csv_f = csv.reader(f, delimiter=',')

    for row in csv_f:
        l.append(log(float(row[1])))

print l

输出:

-4.09835258362
-4.09835258362
-3.40520540306
-2.99974029495
-2.71220883625
-2.30669352104
-1.90119494293

如果不是大文件,

import re
with open('file.txt') as f:
    print(re.findall('\d*?\.\d+', f.read()))

拆分和IndexError: list index out of range异常

words 变量中你得到 hub,0.0166\n 值。

所以 splitline = words.split() 不适合你,因为默认 split 使用 space, \n, \t 拆分字符串。

使用splitline = words.strip().split(",")拆分字符串。

类型转换

由于 splitline 的第一项是 string type,所以我们不能转换为浮点数。

float(splitline[0]) 是不正确的说法。

变量名

  1. newDict: 你将newDict变量定义为list,给变量赋予专有名称,因为根据名称变量类型是字典,但不是大小写.将名称命名为 newList 或 'result_list' 或任何有意义的名称。

  2. 你定义newDict为列表结构,你像字典一样赋值。 newDict[splitline[0]] = ",".join(splitline[1:]) 这将不起作用,因为 newDict 是列表,而不是字典数据类型。

  3. file : 文件是Python中的保留字,不要使用变量名等名称。

您犯的错误是您的代码假定每个 splitline 列表中始终至少有两个项目。如果 a) 该行没有 .split() 函数的有效分隔符,或者 b) 你有一个空行。因此,splitline[1] returns 您看到的 IndexError

如 faost 所述,您需要将 .split() 的分隔符指定为 ',',因为 .split() 使用 space 作为默认分隔符。

您提到文本文件包含 "new lines",我认为这意味着空行?如果是这种情况,您需要在代码中考虑到这一点。您可以检查列表的长度,并确保仅在其长度大于 1 时对其进行操作:

new_list = []
for row in data:
  split_row = row.split(',')
  if len(split_row) > 1:
    new_list.append(float(split_row[1]))

这将从您的文本文件中提取所有浮点值并将它们作为浮点值存储在一个列表中。