将列表从iPython单元格移动到数据文件中
我有以下数据,当前存储在Python列表中:将列表从iPython单元格移动到数据文件中,python,list,file,csv,ipython,Python,List,File,Csv,Ipython,我有以下数据,当前存储在Python列表中: formant_data = [ 'ɑ', 125, 150, 10, 580, 50, 10, 780, 50, 9, 1010, 50, 10, 2530, 100, 9, 4400, 150, 8, 5300, 200, 8, 5880, 200, 7, 7420, 200, 7, 8860, 200, 7, 'a'
formant_data = [
'ɑ',
125, 150, 10,
580, 50, 10,
780, 50, 9,
1010, 50, 10,
2530, 100, 9,
4400, 150, 8,
5300, 200, 8,
5880, 200, 7,
7420, 200, 7,
8860, 200, 7,
'a',
168, 120, 10,
680, 50, 9,
1000, 50, 9,
1500, 150, 8,
2500, 200, 7,
5200, 800, 7,
7200, 400, 6,
8500, 400, 6,
'ɛ',
150, 120, 10,
700, 50, 8,
750, 50, 8,
1800, 150, 8,
]
我将按如下方式打开包装:
import numpy as np
vowels = deque()
acc = deque()
for x in reversed(formant_data):
if isinstance(x,str):
symbol = x
print(symbol)
data = np.reshape( acc, (-1,3) )
vowels.appendleft(data)
acc.clear()
else:
acc.appendleft(x)
return vowels
with open('input.txt', 'r') as input:
content = input.read()
list = content.split(',')
我希望将数据移动到文本文件中,并将其读入
最简单的方法是什么
我不介意摆弄数据文件格式。主要目的是使其易于阅读
编辑:也许我可以将其保存为data.py
和import data.py
?问题:我希望它驻留在input/data.py
编辑:%RunMagic?选项1:(与您的编辑类似) 您可以简单地将列表存储在名为
data\u file.py的文件中,然后从数据文件导入*
选项2:(在评论中给出)
效率更高,但理解起来有点棘手。您可以简单地将列表存储在名为data\u file.py的文件中,然后在代码中执行以下操作:
container = {}
exec(open('data_file.py').read(), container)
选项3:
您可以将列表中的所有内容存储在.txt或任何文件中,然后读取文件的所有内容并按“,”将其拆分,如下所示:
import numpy as np
vowels = deque()
acc = deque()
for x in reversed(formant_data):
if isinstance(x,str):
symbol = x
print(symbol)
data = np.reshape( acc, (-1,3) )
vowels.appendleft(data)
acc.clear()
else:
acc.appendleft(x)
return vowels
with open('input.txt', 'r') as input:
content = input.read()
list = content.split(',')
然后,您就可以对列表执行任何您想执行的操作。为了比import
或exec
更安全,在保持可读性的同时,使用标准模块:
要保存:
import json
with open( filename, 'wt' ) as datafile:
json.dump( formant_data, datafile, indent=3 )
要加载:
import json
with open( filename, 'rt' ) as datafile:
formant_data = json.load( datafile )
这为您提供了设置数据格式的灵活性json
序列化支持dict
类型,这可能是将数字与每个音素关联起来的一种更自然的方式。很抱歉晚才将iPython添加到问题中——我认为这与此无关,但事实证明iPython有一个%的运行
魔法:
%run input/formant_data.py
在我继续讨论这个问题的时候,我很感激其他的答案。我认为,import
需要,因为文件不在当前文件夹中。使用execfile
而不是import
。如果您想控制变量的结束位置,可以说container={};execfile(文件名,容器)
。首选execfile
而不是import
的原因是,一旦导入data.py
一次,它的内容将被缓存,同一文件的后续导入将产生旧数据,而不管最近的更改如何。使用import
或execfile
,请注意安全问题,因为您允许您的解释器执行用良性或非良性“数据”文件编写的任意命令。您是对的,但是execfile
并非对所有python版本都有效argh why python why?删除了可选的基于pickle
的代码,因为pickle
也不安全。