2012-12-25 119 views
0

我有一個文件格式如下。在python中創建字典

>abc 
qqqwqwqwewrrefee 
eededededededded 
dededededededd 
>bcd 
swswswswswswswws 
wswswsddewewewew 
wrwwewedsddfrrfe 
>fgv 
wewewewewewewewew 
wewewewewewewxxee 
wwewewewe 

我試圖創建與字典(> ABC,> BCD,> FGV)作爲鍵和它們下面的字符串作爲值。我可以提取密鑰,但更新值時感到困惑。幫助我請。

file2 = open("ref.txt",'r') 
for line in file2.readlines(): 
    if ">" in line: 
    print (line) 

回答

0
d={} 
key='' 
file2 = open("ref.txt",'r') 
for line in file2.readlines(): 
    if line.startswith('>'): 
     key=line.strip() 
     d[key]=[] 
     continue 
    d[key].append(line.strip()) 
file.close() 

我沒有測試上面的代碼,但它應該工作

1

當你得到一行值爲'>'時,將行保存在一個變量中。當您讀取一行而沒有'>'時,將其添加到以前保存的變量鍵入的字典條目中。

key = None 
dict = {} 
for line in file2.readlines(): 
    if ">" in line: 
     key = line 
     dict[key] = '' # Initialise dictionary entry 
    elif key is not None: 
     dict[key] += line # Append to dictionary entry 
3

不知道你的意思是關於 「更新」 的價值觀,但試試這個:

mydict=[] 
with open("ref.txt", "r") as file2: 
    current = None 
    for line in file2.readlines(): 
     if line[0] == ">": 
      current = line[1:-1] 
      mydict[current] = "" 
     elif current: 
      mydict[current] += line # use line[:-1] if you don't want the '\n' 

In [2]: mydict 
Out[2]: {'abc': 'qqqwqwqwewrrefee\neededededededded\ndededededededd\n', 
     'bcd': 'swswswswswswswws\nwswswsddewewewew\nwrwewedsddfrrfe\n', 
     'fgv': 'wewewewewewewewew\nwewewewewewewxxee\nwwewewewe\n'} 
+0

該值是完整的字符串,不是列表。我的意思是鍵是abc,值是整個字符串(它下面的字符) – gthm

+0

您的鍵(當前變量)包含「\ n」 – Goranek

+0

修復了您的喜好。 – 2012-12-25 11:05:48

1
dictionary = {} 
with open("file.txt","r") as r: 
    for line in r.readlines(): 
     if ">" in line: 
      key = line[1:].strip() 
      dictionary[key] = "" 
     else: 
      dictionary[key] += line 

print(dictionary)