python从外部文件添加到字典

时间:2012-10-26 22:29:33

标签: python file-io dictionary

我有一个外部文件,我需要在字典中。每篇文章都以<NEW DOCUMENT>开头,我不知道如何从文件中提取所有信息,从<newdoc>下面的行开始,到达另一个<newdoc>之前结束。这是我到目前为止所拥有的。

for line in file2:
    line = line.strip()
    line_list = line.split()
    if "NEW DOCUMENT" in line:
        doc_num+=1
        new_dict[doc_num] = line
        print(new_dict)

文件看起来像这样。

<NEW DOCUMENT>
Look on the bright 
side of Life.
<NEW DOCUMENT>
look on the very, dark
side of the Moon

3 个答案:

答案 0 :(得分:2)

以下是对您的解决方案的修改:

docs = []
document = []
for line in file2:
    line = line.strip()
    if line == "<NEW DOCUMENT>":
        # start a new document
        document = []
        docs.append(document)
    else:
        # append to the current one
        document.append(line)

# convert lists of lines into a string
docs = ['\n'.join(document) for document in docs]

答案 1 :(得分:0)

这将为你做到:

docs = file2.read().split("<NEW DOCUMENT>\n")

它为您提供了一个列表,而不是字典,因为为什么您需要一个键是序列号的字典?但如果您必须有字典,请使用:

new_dict = dict(enumerate(docs))

答案 2 :(得分:0)

类似的东西:

In [7]: with open("data1.txt") as f:
    data=f.read()
    dic=dict((i,x.strip()) for i,x in enumerate(data.split("<NEW DOCUMENT>")[1:]))
    print dic
   ....:     
   ....:     
{0: 'Look on the bright \nside of Life.', 1: 'look on the very, dark\nside of the Moon'}