Python 中的 Eval 函数

发布于 2024-10-06 20:10:05 字数 441 浏览 0 评论 0原文

你好,我有以下代码:

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( ) 函数。我想将我作为输入获得的字符串转换为我可以使用的浮点数..

提前感谢任何提示

Hello there i have the following code:

path = some destination on your harddrive

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]

to import a textfile, now my problem is to avoid the \n, which i assume can be done using the eval() function. I want to convert the string i get as input, to floats i can work with..

Thanx for any tips in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

熟人话多 2024-10-13 20:10:05

暗示:

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

Hint:

>>> float("\n1234\n")
1234.0
梦幻的心爱 2024-10-13 20:10:05

我不会评论您的代码,只是发布一个示例,您可以检查和修改以使其正常工作。此函数读取文本文件的内容,并在可能的情况下将由空格分隔的标记转换为浮点数:

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()

I won't comment your code, just will post an example you can examine and modify to get it working. This function reads the content of a text file and converts tokens separated by whitespaces to floats if possible:

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()
月寒剑心 2024-10-13 20:10:05

您的代码非常混乱...要读取每行包含一个浮点数的文件,您可以简单地执行以下操作:

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

val 将是一个包含数据的列表,每个元素都是浮点数

your code is quite confused... to read a file that contains one float per line you can simply do:

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

val will be a list containing your data with each element being a float

陌伤浅笑 2024-10-13 20:10:05

ast.literal_eval() 会将每一行转换为元组,然后您可以对这些值进行迭代或索引。

ast.literal_eval() will turn each line into tuples that you can then iterate or index for the values.

合约呢 2024-10-13 20:10:05

这是一个函数 read_numbers(),它返回浮点数列表的列表。

def read_numbers(filename):
    numbers = []
    with open(filename) as f:
        for line in f:
            lst = [float(word) for word in line.split(',')]
            numbers.append(lst)
    return numbers

如果您的文件包含:

1, 2
2, 3
7, 5

那么 read_numbers('filename') 将返回:

[[1.0, 2.0], [2.0, 3.0], [7.0, 5.0]]

您可能希望通过扩展内部列表理解并将调用包装到 来进行错误处理(或简单地忽略错误) try ... except ValueError 中的 float()

Here's a function read_numbers() which returns a list of lists of floats.

def read_numbers(filename):
    numbers = []
    with open(filename) as f:
        for line in f:
            lst = [float(word) for word in line.split(',')]
            numbers.append(lst)
    return numbers

If your file contains:

1, 2
2, 3
7, 5

Then read_numbers('filename') would return:

[[1.0, 2.0], [2.0, 3.0], [7.0, 5.0]]

You may want to do error handling (or simply ignore errors) by expanding out the inner list comprehension and wrapping the call to float() in a try ... except ValueError.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文