Python 中的 Eval 函数
你好,我有以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
暗示:
Hint:
我不会评论您的代码,只是发布一个示例,您可以检查和修改以使其正常工作。此函数读取文本文件的内容,并在可能的情况下将由空格分隔的标记转换为浮点数:
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:
您的代码非常混乱...要读取每行包含一个浮点数的文件,您可以简单地执行以下操作:
val
将是一个包含数据的列表,每个元素都是浮点数your code is quite confused... to read a file that contains one float per line you can simply do:
val
will be a list containing your data with each element being a floatast.literal_eval()
会将每一行转换为元组,然后您可以对这些值进行迭代或索引。ast.literal_eval()
will turn each line into tuples that you can then iterate or index for the values.这是一个函数
read_numbers()
,它返回浮点数列表的列表。如果您的文件包含:
那么
read_numbers('filename')
将返回:您可能希望通过扩展内部列表理解并将调用包装到
来进行错误处理(或简单地忽略错误)
。try ... except ValueError
中的 float()Here's a function
read_numbers()
which returns a list of lists of floats.If your file contains:
Then
read_numbers('filename')
would return: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 atry ... except ValueError
.