Skip to main content
 首页 » 编程设计

python从文本数据中保存信息

2024年11月01日10fff_TT

这是我的代码

#!/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..' 

我的目标是该程序的用户可以选择他想了解更多信息的特定公司,例如该公司成立的年份和员 worker 数示例:公司名称 = Chef,公司成立的年份 = 1965 and number of employees = 10 我不想打印比公司名称更多的信息,因为以后的信息将包含的不仅仅是成立年份和员 worker 数;)看到这么多信息会很困惑^^ 现在我的问题是,我不知道如何保存我收到的有关公司的信息以及如何在此 block 中打印这些信息:

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..' 

请您参考如下方法:

以您的 previous question 为基础,您可以扩展 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..'