2014-10-09 48 views
0

我有這樣的(最終以一個空行)的文件分割線成的cols

1 hello hello 
4 hello1 
... 
<emptyline> 

我希望把它做成格式 {"hello hello":1, "hello1":4}的字典...關鍵是字符串,值是整數

我現在做

dic={} 
for line in open(file,'rb'): 
    if line.strip: 
     idx=line.find(" ") 
     cnt=int(line[:idx]) 
     key=line[idx+1:] 
     dic[key]=cnt 

有沒有更好的或者更短的方式與numpy的或其他的方法來做到這一點?

回答

3

您可以split並使用1的第二個參數來僅拆分1次。

with open('file.txt', 'r') as f: 
    d = {} 
    for line in f: 
     if line.strip(): 
      value, key = line.split(' ',1) 
      d[key] = int(value) 

爲了削減下來到字典理解

with open('file.txt', 'r') as f: 
    d = {key:int(value) for value,key in [line.split(' ',1) for line in f if line.split()]} 
1
d = {} 
with open('file2.txt') as f: 
    for l in f: 
     s = l.split(' ') 
     d[s[1]] = s[0] 
     print d 
+1

此次榮獲」處理'hello hello'的權利,是嗎? – hpaulj 2014-10-09 19:58:35

+0

它也不會處理空白行 – CoryKramer 2014-10-10 11:36:06

0

最短我可以得到的,而且應該是足夠的效率,但也有點神祕:)

with open('file.txt', 'r') as f: 
    rows = map(lambda l: l.strip().partition(' '), f) 
    d = { r[2]: int(r[0]) for r in rows if r[2] }