0

我有一个格式如下的文件。

>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)
4

4 回答 4

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'}
于 2012-12-25T10:48:10.680 回答
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
于 2012-12-25T10:46:31.600 回答
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)
于 2012-12-25T10:49:56.257 回答
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()

我没有测试上面的代码,但它应该可以工作

于 2012-12-25T10:48:55.347 回答