0

我有一个需要放入字典的外部文件。每篇文章都以 开头<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
4

3 回答 3

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]
于 2012-10-26T22:34:24.370 回答
0

这将为您完成:

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

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

new_dict = dict(enumerate(docs))
于 2012-10-26T22:34:27.707 回答
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'}
于 2012-10-26T22:35:44.970 回答