Python 从文本文件创建字典

Python 从文本文件创建字典,python,dictionary,text-files,Python,Dictionary,Text Files,好吧,我正试图从一个文本文件中创建一个字典,所以键是一个小写字符,每个值是文件中以该字母开头的单词列表 文本文件每行包含一个小写单词,例如: airport bathroom boss bottle elephant 输出: words = {'a': ['airport'], 'b': ['bathroom', 'boss', 'bottle'], 'e':['elephant']} 我还没有做很多工作,只是弄不清楚如何从每行中获取第一个索引,并将其设置为键并附加值。如果有人能帮我穿上衣服

好吧,我正试图从一个文本文件中创建一个字典,所以键是一个小写字符,每个值是文件中以该字母开头的单词列表

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

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

让我们来看看你的例子:

words = {}
for line in infile:
  line = line.strip()
这看起来是个好的开始。现在,您需要对
执行一些操作。您可能需要第一个字符,可以通过
行[0]
访问:

  first = line[0]
然后,您要检查该字母是否已经在dict中。如果没有,您可以添加一个新的空列表:

  if first not in words:
    words[first] = []
然后您可以将单词附加到该列表中:

  words[first].append(line)
你完了

如果行已按示例文件中的方式排序,您还可以使用,这有点复杂:

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), ...)

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']})
导入集合 >>>words=collections.defaultdict(列表) >>>将open('/tmp/spam.txt')作为f: ... lines=[l.strip()表示f中的l,如果l.strip()] ... >>>线条 [‘机场’、‘浴室’、‘老板’、‘瓶子’、‘大象’] >>>对于行中的单词: ... 单词[word[0]]。追加(单词) ... >>>印刷文字 defaultdict(,{'a':['airport'],'b':['Bathy','boss','bottle'],'e':['elephant']})
这是家庭作业吗?到目前为止你想出了什么?到目前为止你尝试了什么?你能在你的问题中加入到目前为止你已经尝试过的代码,这样我们就可以看到你需要更多的帮助了吗?谢谢你的回复,但是我并不熟悉这个方法,因为我们还没有学会。所以我不确定我是否可以使用它。我正在用我的allready和一些我发现的东西做一个for循环。如果你不愿意,你可以试着帮我修一下mind@Who:好的,我用一种更简单的方法添加了一个小的漫游:)非常感谢漫游,它帮了我很大的忙..这正是我想要的..要试试吗