例如,我有一个多行文件,比如
<<something>> 1, 5, 8
<<somethingelse>> hello
<<somethingelseelse>> 1,5,6
我需要用钥匙创建dict
dict = { "something":[1,5,8], "somethingelse": "hello" ...}
我需要以某种方式读取里面的内容,并将其作为一个键,还需要检查元素是否很多或只有1个。如果只有一个,我就把它当作弦。如果超过一个,那么我需要把它作为一个元素列表。 有什么办法帮我吗? 也许是正则表达式,但我对它们不太好。你知道吗
我很容易地创建了def,它读取一个文件行,但不知道如何分离这些值:
f = open('something.txt', 'r')
lines = f.readlines()
f.close()
def finding_path():
for line in lines:
print line
finding_path()
f.close()
有什么想法吗?谢谢:)
假设您的键总是单个单词,您可以使用split(char, maxSplits)。像下面这样
使用下面这样的文件
我得到输出
我的答案与Dinesh的类似,我添加了一个函数,如果可能的话,可以将列表中的值转换为数字,并添加了一些错误处理,这样如果一行不匹配,就会给出有用的警告。你知道吗
输出
请检查以下代码:
使用regex获取键和值
如果值列表的长度为1,则将其转换为字符串。
输出:
相关问题 更多 >
编程相关推荐