从txt文件Python

时间:2015-12-01 10:57:37

标签: python list loops dictionary text-files

我正在尝试使用带有列表的文本文件获取输入值并以适当的输出格式对它们进行排序,但是我很难尝试创建循环并创建此字典。

我创建了一个空白词典但是我不确定我是否应该创建一个字典来获得输出:

foodweb =
{
  “Bird”: [
    Prawn,
    Mussels,
    Crab,
    Limpets,
    Whelk
  ],
  “Crab”: [
    Mussels,
    Limpets
  ],
  “Fish”: [
    Prawn
  ],
  “Limpets”: [
    Seaweed
  ],
  “Lobster”: [
    Crab,
    Mussels,
    Limpets,
    Whelk
  ],
  “Mussels”: [
    Phytoplankton,
    Zooplankton
  ],
  “Prawn”: [
    Zooplankton
  ],
  “Whelk”: [
    Limpets,
    Mussels
  ],
  “Zooplankton”: [
    Phytoplankton
  ]
}

如何编写循环以使其更简单?!?

file_content = open('AquaticFoodWeb.txt' , 'r')
aquaticfoodweb ={}
for line in file_content:
    myList=line.rstrip('\n').split(" eats ")

这是txt文件中的列表

Bird eats Prawn
Bird eats Mussels
Bird eats Crab
Bird eats Limpets
Bird eats Whelk
Crab eats Mussels
Crab eats Limpets
Fish eats Prawn
Limpets eats Seaweed
Lobster eats Crab
Lobster eats Mussels
Lobster eats Limpets
Lobster eats Whelk
Mussels eats Phytoplankton
Mussels eats Zooplankton
Prawn eats Zooplankton
Whelk eats Limpets
Whelk eats Mussels
Zooplankton eats Phytoplankton

这是我正在努力的理想输出格式:

Predators and Prey:
Bird eats Prawn, Mussels, Crab, Limpets and Whelk
Crab eats Mussels and Limpets
Fish eats Prawn
Limpets eats Seaweed
Lobster eats Crab, Mussels, Limpets and Whelk
Mussels eats Phytoplankton and Zooplankton
Prawn eats Zooplankton
Whelk eats Limpets and Mussels
Zooplankton eats Phytoplankton

4 个答案:

答案 0 :(得分:1)

像这样:

    file_content = open('AquaticFoodWeb.txt' , 'r')
    aquaticfoodweb ={}
    for line in file_content.readlines():
        aquaticfoodweb.setdefault(line.split()[0], []).append(line.split()[-1])
    file_content.close()
    for key, value in aquaticfoodweb.items():
        if len(value) > 1:
            value = value[:-2] + [" and ".join(value[-2:])]
        print "{} eats {}".format(key, ",".join(value))

如果key不在dict中,则setdefault方法设置dict [key] = default。

答案 1 :(得分:1)

我不确定您是要求输出文字还是要求字典。您可以像这样创建字典:

file_content = open('AquaticFoodWeb.txt' , 'r')
aquaticfoodweb ={}
for line in file_content:
    myList=line.rstrip('\n').split(" eats ")
    try:
        aquaticfoodweb[myList[0]].append(myList[1])
    except KeyError:
        aquaticfoodweb[myList[0]]=[myList[1]]

try except会在字典中创建一个新条目(如果它尚未存在)(确保新条目是一个列表),如果该条目已经存在,它将附加到列表中。

答案 2 :(得分:1)

希望以下内容有所帮助。你需要从一个空字典开始。对于输入的每一行,您正确地分割输入的两个部分。然后,您可以使用它们来创建字典条目。字典中的每个条目都是一个列表。 setdefault用于在找到新动物时创建空列表,然后自动将猎物追加到该列表中。

最后,输出需要一些考虑,以确保具有多个猎物的项目添加and输出。由于没有订购字典,您需要在显示结果之前对其进行排序:

foodweb = {}

with open('AquaticFoodWeb.txt') as f_input:
    for line in f_input:
        animal, prey = line.strip().split(' eats ')
        foodweb.setdefault(animal, []).append(prey)

print "Predators and Prey:"

for animal, prey in sorted(foodweb.items()):
    if len(prey) > 1:
        print "{} eats {} and {}".format(animal, ", ".join(prey[:-1]), prey[-1])
    else:
        print "{} eats {}".format(animal, ", ".join(prey))

这将为您提供以下输出:

Predators and Prey:
Bird eats Prawn, Mussels, Crab, Limpets and Whelk
Crab eats Mussels and Limpets
Fish eats Prawn
Limpets eats Seaweed
Lobster eats Crab, Mussels, Limpets and Whelk
Mussels eats Phytoplankton and Zooplankton
Prawn eats Zooplankton
Whelk eats Limpets and Mussels
Zooplankton eats Phytoplankton

答案 3 :(得分:0)

你可以使用正则表达式吗?如果文件不大可能适合

import re

with open('AquaticFoodWeb.txt' , 'r') as f:
   content = f.read()

foodweb = re.findall('(\"(.*?)\").*?\[(.*?)\]') 

for item in foodweb:
   idx = item[1].rfind(", ")
   print "%s eats %s" % (item[0],item[1][0:idx]+item[1][idx:].replace(", ", " and "))