【问题标题】:Creating a Dictionary from File [duplicate]从文件创建字典 [重复]
【发布时间】:2012-10-29 12:22:22
【问题描述】:

可能重复:
Reading a File into a Dictionary And Keeping Count

我正在尝试创建一个包含两个值的字典:第一个值是文本:

<NEW ARTICLE>
Take a look at 
what I found.
<NEW ARTICLE>
It looks like something
dark and shiny.
<NEW ARTICLE>
But how can something be dark
and shiny at the same time?
<NEW ARTICLE>
I have no idea.

第二个值是单词“ARTICLE>”被使用的次数。

我尝试了不同的方法,其中一种方法收到此错误:

我收到的错误是这样的:

(key, val) = line.split()
ValueError: need more than 1 value to unpack

我尝试了几种不同的方法,但都无济于事,我尝试的一种方法说它提供了太多的值来解压..

我希望以后能够在字典中搜索关键字/单词并找到其适当的计数。

使用 Python 3。

【问题讨论】:

  • 你问了同样的问题here。重复问同一个问题通常不是一个好主意

标签: python list function dictionary


【解决方案1】:

应该这样做:

>>> with open("data1.txt") as f:
...     lines=f.read()
...     spl=lines.split("<NEW ARTICLE>")[1:]
...     dic=dict((i,x.strip()) for i,x in enumerate(spl))
...     print dic
... 
{0: 'Take a look at \nwhat I found.',
 1: 'It looks like something\ndark and shiny.',
 2: 'But how can something be dark\nand shiny at the same time?',
 3: 'I have no idea.'}

【讨论】:

  • 嗯,我打印时总是得到一个空字典,我使用的是 Python 3。
  • @Goose 刚刚在 python 3.x 上进行了测试,效果很好。
  • 它有效,但是这个概念对于新手来说有点棘手,你能解释一下什么是“dic=dict((i,x.strip()) for i,x in enumerate(spl))" 完全符合您的答案吗?然后我可以选择它为正确的。
  • @Goose lines.split("&lt;NEW ARTICLE&gt;") 实际上在wherever它找到"&lt;NEW ARTICLE&gt;",并返回一个类似['\nTake a look at \nwhat I found.\n', '\nIt looks like something\ndark and shiny.\n', '\nBut how can something be dark\nand shiny at the same time?\n', '\nI have no idea.\n'] 的列表,1[:] 用于从中删除第一个元素列表是一个空字符串。
  • @Goose 现在下一步很简单,因为我们只需使用enumerate() 遍历列表,因为它返回索引以及列表中的项目,因此使用该数据我们创建一个dict 使用 dict()。其中keyindexvalueitem
【解决方案2】:

确保某处没有空行:

if newdoc == True and line != "ARTICLE>" and line:
    (key, val) = line.split()

(空行会被拆分为[],不能解析为包含两个元素的元组...)

【讨论】:

  • 还有一个问题:line != "ARTICLE&gt;" 永远为真。
  • 但如果line=="",则不满足条件。
  • 是的,但他的行中没有一条与"ARTICLE&gt;"完全相同,所以代码肯定行不通。也许not line.endswith("ARTICLE&gt;")...
猜你喜欢
  • 1970-01-01
  • 2016-02-27
  • 2018-03-12
  • 1970-01-01
  • 2016-09-03
  • 2013-12-06
  • 2011-10-08
  • 2012-12-15
  • 2018-03-29
相关资源
最近更新 更多