python从外部文件添加到字典

python从外部文件添加到字典,python,file-io,dictionary,Python,File Io,Dictionary,我有一个需要放入字典的外部文件。每篇文章都以开头,我不知道如何从文件中提取所有信息,从下面的行开始,在到达另一行之前结束。这是我到目前为止所拥有的 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_dic

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

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

乐观
生活的另一面。
看那黑暗的天空
月面

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

docs=[]
文件=[]
对于文件2中的行:
line=line.strip()
如果行==“”:
#开始新文档
文件=[]
docs.append(文档)
其他:
#附加到当前文件
document.append(行)
#将行列表转换为字符串
docs=['\n'。为docs中的文档加入(文档)]
这会帮你做到:

docs = file2.read().split("<NEW DOCUMENT>\n")
大概是这样的:

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'}
[7]中的
:以open(“data1.txt”)作为f:
data=f.read()
dic=枚举(data.split(“”[1:])中i,x的dict((i,x.strip())
打印dic
....:     
....:     
{0:'看生活的光明面',1:'看月亮的黑暗面'}

将所有行连接在一起,我试图让它们成为单独的文档,例如查找文档1让我看到生活的光明面,2让我看到月亮的光明面,我只想在打印时忽略,并且能够调用1并能够读取document@Ryan:非常确定这就是我在
docs[0]
etchow中所做的(未经测试…),我会对其进行修改以搜索文档中的不同项目,例如,如果我想知道哪个文档包含“moon”只是对你所有答案的一般性评论-为什么我需要在[7]中看到
..:
?@Eric这些都是因为我使用
IPython
shell。这解释了为什么它们不是
,但这不是我的问题。你在记分吗“听着,我这么做了,我试了7次”
new_dict = dict(enumerate(docs))
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'}