编程语言
首页 > 编程语言> > python-从文本文件创建字典

python-从文本文件创建字典

作者:互联网

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

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

airport
bathroom
boss
bottle
elephant

输出:

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

Havent确实做了很多工作,只是感到困惑,我该如何从每行中获取第一个索引并将其设置为键并附加值.如果有人可以帮助我进行交易,我将不胜感激.

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]

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

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

标签:dictionary,text-files,python
来源: https://codeday.me/bug/20191201/2081698.html