2

这是我的代码

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import re

#read information

f = open ("/home/ibrahim/Desktop/Test.list")

text = f.read()

#show existing companys

for line in open('/home/ibrahim/Desktop/Test.list'):
    company, founding_year, number_of_employee = line.split(',')
    print "Company: %s" % company

#User chooses a company he wants to know more about

CompanyIndex = raw_input('\n<Choose a company you want to know more about.>\n\n<Insert a companyspecific-number and press "Enter" .>\n')

#Companyspecific information is getting revealed

if CompanyIndex == '1':
        print #company1,founding_year1,number_of_employee2
elif CompanyIndex == '2':
        print #company2,founding_year2,number_of_employee2
elif CompanyIndex == '3':
        print #company3,founding_year3,number_of_employee3
else:
        print 'Your input is not correct..'

我的目标是该程序的用户可以选择他想了解更多的特定公司,例如该公司成立的年份和员工人数示例:公司名称 = 厨师,公司成立年份 = 1965 和人数employees = 10 我不想打印超过公司名称的信息,因为未来的信息将不仅仅包含创始年份和员工人数;)看到这么多信息会很混乱^^现在我的问题是,我不知道如何保存收到的有关公司的信息以及如何在此块中打印这些信息:

if CompanyIndex == '1':
        print #company1,founding_year1,number_of_employee2
elif CompanyIndex == '2':
        print #company2,founding_year2,number_of_employee2
elif CompanyIndex == '3':
        print #company3,founding_year3,number_of_employee3
else:
        print 'Your input is not correct..'
4

3 回答 3

1

将其添加到混合物中:

# To store info from the text file:
companyDB = []

# Read from file for existing companies

for line in open('/home/ibrahim/Desktop/Test.list'):
    company, founding_year, number_of_employee = line.split(',')
    print "Company: %s" % company

    # Store it locally
    companyDB.append((company, founding_year, number_of_employee))

现在,当用户选择任何数字时:

print companyDB[companyIndex - 1] # Since your first line will be item number 0 in the list
于 2013-09-09T09:28:33.873 回答
1

在您之前的问题的基础上,您可以扩展for循环以将公司数据存储在字典中:

companies = {}
for line in open('/home/ibrahim/Desktop/Test.list'):
    # line is "(Number)Name,Year,Employees"
    company, founding_year, number_of_employee = line.split(',')
    # company is "(Number)Name"
    number, name = company.split(")")
    number = number[1:] # trim '('
    companies[number] = (name, founding_year, number_of_employee)
    print "Company: %s" % company

现在,您可以使用数字作为键从字典中获取信息:

if CompanyIndex in companies:
    name, founding_year, number_of_employee = companies[CompanyIndex]
    # print stuff
else:
    print 'Your input is not correct..'
于 2013-09-09T09:28:51.500 回答
0

您可以使用列表或字典

comapnay_data = [dict(zip(('company', 'founding_year', 'number_of_employee'), line.split(','))) for line in open()]

这将使您的索引通过0。

或者

company_data = {no: dict(zip(('company', 'founding_year', 'number_of_employee'), line.split(','))) for no, line in enumerate(open(), start=1)}

于 2013-09-09T09:32:02.080 回答