Python中的Eval函数

0 投票
5 回答
1639 浏览
提问于 2025-04-16 08:20

你好,我有以下代码:

path = 你硬盘上的某个目标位置

def K(path):
    try:

        getfile = open(path + '/test.txt')
        line = getfile.readlines()
        print line
        getfile.close()

    except:
        line = getfile.readlines()
        eval(line)
        d = dict()
        val= d[k]

用来导入一个文本文件,现在我的问题是如何避免出现 \n,我想这可以通过使用 eval() 函数来实现。我想把我得到的字符串转换成可以使用的浮点数。

提前谢谢任何建议!

5 个回答

1

你的代码有点让人困惑……如果你想读取一个每行都有一个浮点数的文件,可以简单地这样做:

val = map(float, open("test.txt"))

val 将会是一个列表,里面包含你的数据,每个元素都是一个浮点数。

2

提示:

>>> float("\n1234\n")
1234.0
1

我不打算对你的代码进行评论,只是给你一个示例,你可以查看并修改它,让它正常工作。这个函数的作用是读取一个文本文件的内容,并把用空格分开的部分转换成浮点数(小数),如果可以的话:

def getFloats(filepath):
  fd = open(filepath) # open the file
  try:
    content = fd.read().split() # read fully
    def flo(value):  # a function that returns a float for the given str or None
      try: return float(value)
      except ValueError: return None # skip invalid values
    # iterate through content and make items float or None,
    # iterate over the result to choose floats only
    return [x for x in [flo(y) for y in content] if x]
  finally:
    fd.close()

撰写回答