我有以下文本文件:
text1 text2
# text2 text3 text4
# text5 text4 text6
text 3 text 4
# ....
...
我想有一个像下面这样的数组列表
dict[function([text1, text2])] = [[text2, text3, text4], [text5, text4, text6]].
想法是打开文件,逐行读取
dict = {}
inputfile = open("text.txt","r")
for line in inputfile:
l=line.split()
if not line.startswith("#"):
#create a new key
else:
dict[key] = l
但是,问题是,如果我转到下一行,则无法分配其他元素。你知道如何解决这个问题吗?
“函数”只是我在其他地方定义的函数,它以字符串列表作为输入。
您可以collections.defaultdict
用来创建以list
s作为值的字典,可以在其中添加项目。
from collections import defaultdict
my_dict = defaultdict(list)
with open('text.txt') as f:
key = ''
for line in f:
if not line.startswith('#'):
key = line
# key = function(line.split())
continue
my_dict[key].append(line.strip('#').split())
print(my_dict)
输出:
defaultdict(<class 'list'>,
{'text1 text2\n': [['text2', 'text3', 'text4'],
['text5', 'text4', 'text6']],
'text3 text4\n': [['text21', 'text31', 'text41'],
['text51', 'text41', 'text61']]})
只需将key = line
行更改为要将密钥传递给的任何函数。
我的text.txt
文件包含:
text1 text2
# text2 text3 text4
# text5 text4 text6
text3 text4
# text21 text31 text41
# text51 text41 text61
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句