【问题标题】:Create a dictionary from text file从文本文件创建字典
【发布时间】:2012-04-10 12:08:26
【问题描述】:

好吧,我正在尝试从文本文件创建字典,因此键是单个小写字符,每个值都是文件中以该字母开头的单词的列表。

文本文件每行包含一个小写单词,例如:

airport
bathroom
boss
bottle
elephant

输出:

words = {'a': ['airport'], 'b': ['bathroom', 'boss', 'bottle'], 'e':['elephant']}

真的做了很多,只是困惑我如何从每一行获取第一个索引并将其设置为键并附加值。如果有人可以帮助我解决问题,我会非常感激。

words = {}

for line in infile:
  line = line.strip() # not sure if this line is correct

【问题讨论】:

  • 这是作业吗?到目前为止你有什么想法?
  • 到目前为止你尝试过什么?您能否在问题中包含您迄今为止尝试过的代码,以便我们了解您在哪里需要更多帮助?

标签: python dictionary text-files


【解决方案1】:

让我们来看看你的例子:

words = {}
for line in infile:
  line = line.strip()

这看起来不错。现在你想用line 做点什么。可能您需要第一个字符,您可以通过line[0] 访问:

  first = line[0]

然后您要检查该字母是否已在字典中。如果没有,您可以添加一个新的空列表:

  if first not in words:
    words[first] = []

然后您可以将单词附加到该列表中:

  words[first].append(line)

你就完成了!

如果这些行已经像示例文件中那样排序,您还可以使用itertools.groupby,它更复杂一点:

from itertools import groupby
from operator import itemgetter

with open('infile.txt', 'r') as f:
  words = { k:map(str.strip, g) for k, g in groupby(f, key=itemgetter(0)) }

你也可以先对行进行排序,这使得这种方法普遍适用:

groupby(sorted(f), ...)

【讨论】:

  • 感谢您的回复,但我实际上并不熟悉这种方法,因为我们还没有学会它。所以我不确定我是否可以使用它。
  • 我正在使用我已经拥有的东西和我发现的一些东西来处理 for 循环。如果你不介意的话,你可以试着帮我解决这个问题
  • @Who:好的,我使用更简单的方法添加了一个小演练:)
  • 非常感谢帮助很大的演练..这正是我正在寻找的..会试一试
【解决方案2】:

collections 模块中的defaultdict 是此类任务的不错选择:

>>> import collections
>>> words = collections.defaultdict(list)
>>> with open('/tmp/spam.txt') as f:
...   lines = [l.strip() for l in f if l.strip()]
... 
>>> lines
['airport', 'bathroom', 'boss', 'bottle', 'elephant']
>>> for word in lines:
...   words[word[0]].append(word)
... 
>>> print words
defaultdict(<type 'list'>, {'a': ['airport'], 'b': ['bathroom', 'boss', 'bottle'], 'e': ['elephant']})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 2013-07-13
    • 1970-01-01
    相关资源
    最近更新 更多