^[\s\S]{0,255}$
以上是我的代码。因此要求是从.csv文件加载数据到元组列表。文件中的数据类似于:
def loadfunc(filestr):
listoftuples = []
listofnumbers = []
tupleinlist = []
with open(filestr, 'r') as file:
for line in file:
for item in line:
if item.isdigit():
listofnumbers.append(float(item))
else:
word = item
tupleinlist.append(word)
tupleinlist.append(listofnumbers)
listoftuples.append(tuple(tupleinlist))
return listoftuples
print(listoftuples)
对于列表中的每个元组,它必须是 - apple 23.2 24.3 25.6
- banana 22.1 20.0 19.9
,所以列表看起来像:
(word, listoffloats)
但是使用我的代码会将其搞砸并且不会返回它,因为当它在每个“行”中迭代“item”时,它会迭代每个字符(例如[(apple, [23.2, 24.3, 25.6]), (banana, [22.1, 20.0, 219.9])]
,.
, a
,p
,p
,l
)而不是项目如e
,apple
等。
请帮助我不知道如何解决这个问题,不允许在本教程中使用csv库/模块。
答案 0 :(得分:1)
让我们说你有t.csv中的数据。您可以将数据保存在split
列表中,然后在文件的每一行使用results
,并将拆分结果附加到split
。使用csv模块可以为您完成此操作,但您可以使用with open('t.csv', 'r') as f:
results = []
for line in f:
words = line.split(',')
results.append((words[0], words[1:]))
print results
复制分隔符行为。
lessons.insert({
name: 'some_name',
audio_files: [
[
{
paths: 'paths/to/file1',
transcriptions: [
'Transcript ..........1',
'Transcript ..........2',
'Transcript ..........3',
]
}
],
[
{
paths: 'paths/to/file2',
transcriptions: [
'Transcript ..........1',
'Transcript ..........2',
'Transcript ..........3',
]
}
],
]
});
答案 1 :(得分:0)
考虑输入文件包含
之类的输入# in.txt
# apple 23.2 24.3 25.6
# banana 22.1 20.0 19.9
# end
from collections import defaultdict
def get_word_float(infile_str):
d = defaultdict(list)
with open(infile_str) as inf:
for l in inf:
item = l.split() # split by space
d[item[0]].extend(map(float, item[1:]))
return d
print(get_word_float('in.txt'))
# defaultdict(<class 'list'>, {'apple': [23.2, 24.3, 25.6], 'banana': [22.1, 20.0, 19.9]})
答案 2 :(得分:0)
with open('a.csv', 'r') as f:
#read from csv line by line, rstrip helps to remove '\n' at the end of line
lines = [line.rstrip() for line in f]
results = []
for line in lines:
words = line.split(',')#get each item in one line
listOfFloat = map(float,words[1:])# convert string to float
tup = (words[0],listOfFloat)
results.append(tup)
print results