2012-12-25 89 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)