我有一个格式如下的文件。
>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 :(得分: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'}
答案 1 :(得分: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
答案 2 :(得分: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)
答案 3 :(得分: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()
我没有测试过上面的代码,但它应该可以正常工作