Python读取文件打印几个信息

时间:2013-09-06 09:03:20

标签: python

我收到了以下代码:

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

import sys

#read information
f = open ("/home/ibrahim/Desktop/Test.list")
text = f.read()

#show existing companys
Companyname = text.split("\n")
print Companyname

#User chooses a company he wants to know more about
raw_input('\n<Wählen Sie die Firma Ihrer Wahl aus um die Informationen anzuzeigen.>\n\n<Geben Sie die Firmenspezifische Zahl ein und b$

#Companyspecific information is getting revealed

Test.list 看起来像这样

(1)Chef,1965,10
(2)Fisher,1932,20
(3)Gardener,1998,5

我的目标是,该计划的用户可以选择他想要了解更多信息的特定公司。例如,该公司开始的那一年和员工数量 示例: 公司名称=主厨公司开始年份= 1965年员工人数= 10 我不想打印超过公司名称,因为未来的信息将包含的不仅仅是创始年份和员工人数。

编辑:糟透了我无法接受每一个答案,也无法向任何人投票,因为我真的很想:SI感谢我从你那里得到的每一个帮助以及编辑我帖子的人所以它看起来好一点^ ^

5 个答案:

答案 0 :(得分:2)

以下是一个工作示例:

#!/usr/bin/env python

for line in open('data.txt'):
    company, year, number_of_employee = line.split(',')
    print "Company: %s" % company

此致

答案 1 :(得分:1)

你可以这样做:

info = text.split("\n")
CompanyName = [inf.split(')')[1].split(',')[0] for inf in info]

答案 2 :(得分:1)

如何使用正则表达式查找几个部分?

import re
with open("Test.list") as f:
    for line in f.readlines():
        m = re.match(r'\((\d)+\)([^,]+),(\d+),(\d+)', line)
        print m.groups()

第一组是ID (\d)+,第二组是名称([^,]+)(除了逗号之外的所有内容),第三组是(\d+),第四组是(\d+) {{1} }}

当然,如果可以将公司名称与ID一起使用,您也可以使用line.split(',')csv

答案 3 :(得分:1)

这是另一个例子,效率更高。

#!/usr/bin/env python
# virtualenv ~/.virtualens/company_reader
# source ~/.virtualenvs/company_reader/bin/activate
# pip install prettytable
# python reader.py
import re 
from collections import namedtuple

# PrettyTable is a tool to format a list of elements with an elegant table.
import prettytable

Company = namedtuple('Company', ['identifier', 'name', 'year', 'nbr_employee'])

company_name = raw_input('Enter the company: ').lower()

# The regexp
pattern_str = r"\((?P<identifier>\d+)\)(?P<name>\w+),(?P<year>\d+),(?P<nbr_employee>\d+)"
pattern = re.compile(pattern_str)

companies = []

# TODO: add a argument parser
# docopt is a correct solution for this purpose
for line in open('data.txt'):
    matching = pattern.match(line)
    # if there is no matching, continue on the next line
    if matching is None:
        continue
    company = Company(*matching.groups())
    if company.name.lower() == company_name:
        companies.append(company)

if not companies:
    print "Sorry, there is no result"
else:
    pt = prettytable.PrettyTable(['Identifier', 'Name', 'Year', 'Number of Employee'])
    pt.align['Identifier'] = 'l'
    pt.align['Name'] = 'l'
    pt.align['Number of Employee'] = 'r'

    for company in companies:
         pt.add_row([company.identifier, company.name, company.year, company.nbr_employee])

    print pt

答案 4 :(得分:0)

您将使用csv阅读器完成此操作。 http://docs.python.org/2/library/csv.html

>>> import csv
>>> list={}
>>> with open('/home/ibrahim/Desktop/Test.list', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=',')
...     for name,year,number in spamreader:
...         id,name = name.split(')',1)
...         list[name] = {'year':year,'number':number,'name':name}
>>> name = raw_input('Enter company name')
>>> print '{name} started at {year} and has {number} workers'.format(**list[name])