从读取的文本文件python3追加列表

2024-10-01 00:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试读取一个txt文件并从文本创建一个字典。txt文件示例如下:

John likes Steak

John likes Soda

John likes Cake

Jane likes Soda

Jane likes Cake

Jim likes Steak

我想要的输出是一个以名称为键的字典,“likes”是各个值的列表:

{'John':('Steak', 'Soda', 'Cake'), 'Jane':('Soda', 'Cake'), 'Jim':('Steak')}

我不断遇到错误,将我的精简单词添加到列表中,并尝试了几种不同的方法:

pred = ()

prey = ()

spacedLine = inf.readline()

line = spacedLine.rstrip('\n')

while line!= "":

    line = line.split()
    pred.append = (line[0])
    prey.append = (line[2])
    spacedLine = inf.readline()
    line = spacedLine.rstrip('\n')

还有:

空间线=inf.readline文件()

line = spacedLine.rstrip('\n')

while line!= "":

     line = line.split()      
     if line[0] in chain:
       chain[line[0] = [0, line[2]]
      else:
        chain[line[0]] = line[2]
    spacedLine = inf.readline()
    line = spacedLine.rstrip('\n')

有什么想法吗?你知道吗


Tags: 文件txtchainreadline字典linejohninf
3条回答

你的输入是一系列的序列。首先解析外部序列,然后解析每个项。你知道吗

你的外部序列是:

Statement
<empty line>
Statement
<empty line>
...

假设f是包含数据的打开文件。阅读每个语句并返回它们的列表:

def parseLines(f):
  result = []
  for line in f:  # file objects iterate over text lines
    if line:  # line is non-empty
      result.append(line)
  return result

注意,上面的函数接受更广泛的语法:它允许在非空行之间任意多个空行,并且一行中有两个非空行。但它接受任何正确的输入。你知道吗

然后,您的语句是一个三元组:X likes Y。通过用空格分割它并检查结构来解析它。结果是一对正确的(x, y)。你知道吗

def parseStatement(s):
  parts = s.split()  # by default, it splits by all whitespace
  assert len(parts) == 3, "Syntax error: %r is not three words" % s
  x, likes, y = parts  # unpack the list of 3 items into varaibles
  assert likes == "likes", "Syntax error: %r instead of 'likes'" % likes
  return x, y

为每个语句列出一个对的列表:

pairs = [parseStatement(s) for s in parseLines(f)]

现在需要按键对值进行分组。让我们使用defaultdict,它为任何新键提供默认值:

from collections import defaultdict

the_answer = defaultdict(list)  # the default value is an empty list

for key, value in pairs:
  the_answer[key].append(value) 
  # we can append because the_answer[key] is set to an empty list on first access

所以这里the_answer是您需要的,只是它使用列表作为dict值而不是元组。这一定足够你理解你的作业了。你知道吗

dic={}

for i in f.readlines():
    if i:
        if i.split()[0] in dic.keys():
            dic[i.split()[0]].append(i.split()[2])
        else:
            dic[i.split()[0]]=[i.split()[2]]

print dic

这样就可以了。你知道吗

在这里,我们遍历f.readlinesf作为file对象,并在每一行上使用split的第一部分作为键,split的最后一部分作为值来填充字典

这样就可以了(无需先将整个文件读入内存):

likes = {}
for who, _, what in (line.split()
                        for line in (line.strip()
                            for line in open('likes.txt', 'rt'))):
    likes.setdefault(who, []).append(what)

print(likes)

输出:

{'Jane': ['Soda', 'Cake'], 'John': ['Steak', 'Soda', 'Cake'], 'Jim': ['Steak']}

或者,为了稍微简化一些,您可以使用一个临时的collections.defaultdict

from collections import defaultdict

likes = defaultdict(list)
for who, _, what in (line.split()
                        for line in (line.strip()
                            for line in open('likes.txt', 'rt'))):
    likes[who].append(what)

print(dict(likes))  # convert to plain dictionary and print

相关问题 更多 >