2011-08-12 13 views
0

私はそれが描かれているファイルは現在、オフィスの外名、姓、オフィスでの日付、および日付をリストされているにもかかわらず、姓のアルファベット順に大統領のリストを取得しようとしています。ここでPythonでファイルをアルファベット順に並べるには?

は、私は、私はこれを行うために必要なもの上の任意の助けを持っているものです。私はいくつかの答えを探し回っており、そのほとんどは私の理解のレベルを超えています。私は何か小さいものを逃しているように感じる。私はそれらをすべてリストに壊して並べ替えようとしましたが、動作させることができませんでしたので、これが私が始まった場所です。

INPUT_FILE = 'presidents.txt' 
OUTPUT_FILE = 'president_NEW.txt' 
OUTPUT_FILE2 = 'president_NEW2.txt' 

def main(): 
    infile = open(INPUT_FILE) 
    outfile = open(OUTPUT_FILE, 'w') 
    outfile2 = open(OUTPUT_FILE2,'w') 

    stuff = infile.readline() 

    while stuff: 
    stuff = stuff.rstrip() 
    data = stuff.split('\t') 

    president_First = data[1] 
    president_Last = data[0] 
    start_date = data[2] 
    end_date = data[3] 

    sentence = '%s %s was president from %s to %s' % \ 
       (president_First,president_Last,start_date,end_date) 
    sentence2 = '%s %s was president from %s to %s' % \ 
       (president_Last,president_First,start_date, end_date) 

    outfile2.write(sentence2+ '\n') 
    outfile.write(sentence + '\n') 

    stuff = infile.readline() 

    infile.close() 
    outfile.close() 

main() 

答えて

2

あなたはすべきことは、大統領をリストに入れ、そのリストをソートし、結果リストをプリントアウトすることです。あなたのループアドオンのための前

:あなたが名前を引き出した後

presidents = [] 

は、forループ内でこのコードを持っている/ループの

presidents.sort() # because we put last_name first above 
# it will sort by last_name 

president = (last_name, first_name, start_date, end_date) 
presidents.append(president) 

をさかのぼりそして、それをプリントアウト:

for president in presidents 
    last_name, first_name, start_date, end_date = president 
    string1 = "..." 

あなたがリストにそれらを破るしようとしたようですね。それに問題があった場合は、その試みに起因するコードを表示してください。問題に近づくのは正しい方法でした。

その他のコメント:

あなたのコードが簡単になる可能性の点だけのカップル。希望としてこれを無視するか、または使用すること自由に感じなさい:

president_First=data[1] 
president_Last= data[0] 
start_date=data[2] 
end_date=data[3] 

は、以下のように書くことができる

for stuff in infile: 
    ... 
0
#!/usr/bin/env python 

# this sounds like a homework problem, but ... 

from __future__ import with_statement # not necessary on newer versions 

def main(): 
    # input 
    with open('presidents.txt', 'r') as fi: 
     # read and parse 
     presidents = [[x.strip() for x in line.split(',')] for line in fi] 
     # sort 
     presidents = sorted(presidents, cmp=lambda x, y: cmp(x[1], y[1])) 
    # output 
    with open('presidents_out.txt', 'w') as fo: 
     for pres in presidents: 
      print >> fo, "president %s %s was president %s %s" % tuple(pres) 

if __name__ == '__main__': 
    main() 

president_Last, president_First, start_date, end_date = data 


stuff=infile.readline() 

そして

while stuff: 
    stuff=stuff.rstrip() 
    data=stuff.split('\t') 
    ... 
    stuff = infile.readline() 

は、のように記述することができます

+1

'sorted'ため' cmp'パラメータ(およびリストの '.sort'方法)は推奨されています。 'key'でうまく機能しないユースケースは、それほど多くないし、一般的には本当に厄介です。 –

0

私は、あなたが「彼ら」とはどういう意味ですか?

をリストにそれらすべてを抜け出すことを試み、その後、ソートそれら

項目のリストに行を分割することは良いスタートです:あなたが値のセット(そのうちの一つ姓がある)だけでなく、文字列としてデータを扱うことを意味します。しかし、のリストをソートするだけでいいわけではありません。 Pythonは、行(姓、名字など)から4文字列を取り出し、順番に並べます。

あなたのやりたいことは、リストのリストであり、をソートしてください。

Pythonのリストには、sortのソート方法があります。それを大統領情報リストのリストに適用すると、大統領情報リストがソートされます。しかし、リストのデフォルトの並べ替えでは、項目ごとに比較されます(最初の項目が最初に、次に最初の項目が等しい場合は2番目の項目など)。サブリストの2番目の要素である姓で比較したいとします。 (つまり、要素1です; 0からリスト要素を数え始めます)

幸いにも、Pythonにより具体的な並べ替えの指示を与えるのは簡単です。ソート関数key引数を渡すことができます。これは、項目を並べ替える値に "変換"する関数です。はい、Pythonではすべてがオブジェクトです - (関数を含む) - 関数をパラメータとして渡すことに問題はありません。したがって、「姓で」ソートする必要があるので、社長情報リストを受け取り、姓(つまり、要素[1])を返す関数を渡します。

幸いにも、これはPythonであり、 "バッテリーは含まれています"。私たちは自分自身でその関数を書く必要はありません。 は、シーケンスのn番目の要素(ここではこれが必要です)を返す関数を作成するという魔法のツールが与えられています。 itemgetter(シーケンスのn番目のアイテムを取得する関数を作成するため、「item」はPythonのより一般的な用語で、「element」はより一般的なCS用語です)、operatorモジュールに存在します。

ところで、ファイルのオープン/クローズを処理するためのきめ細かな方法があります。ファイルを読み込むための明示的なループを記述する必要はありません。ファイルを直接反復処理することができます。for line in file:ファイルの行、ループのたびに1つ)、という意味でlist comprehension(参照してください)という意味です。

import operator 
def main(): 
    # We'll set up 'infile' to refer to the opened input file, making sure it is automatically 
    # closed once we're done with it. We do that with a 'with' block; we're "done with the file" 
    # at the end of the block. 
    with open(INPUT_FILE) as infile: 
    # We want the splitted, rstripped line for each line in the infile, which is spelled: 
    data = [line.rstrip().split('\t') for line in infile] 

    # Now we re-arrange that data. We want to sort the data, using an item-getter for 
    # item 1 (the last name) as the sort-key. That is spelled: 
    data.sort(key=operator.itemgetter(1)) 

    with open(OUTPUT_FILE) as outfile: 
    # Let's say we want to write the formatted string for each line in the data. 
    # Now we're taking action instead of calculating a result, so we don't want 
    # a list comprehension any more - so we iterate over the items of the sorted data: 
    for item in data: 
     # The item already contains all the values we want to interpolate into the string, 
     # in the right order; so we can pass it directly as our set of values to interpolate: 
     outfile.write('%s %s was president from %s to %s' % item) 
0

私はそれが原因私はなっていたいくつかのエラーのために、私のために動作させるために、コードを編集する必要がなかったが、Karlsでの作業、これは上記の助け手に入れました。私はそれらを排除し、これで終わりました。

import operator 

INPUT_FILE = 'presidents.txt' 

OUTPUT_FILE2= 'president_NEW2.txt' 

def main(): 

with open(INPUT_FILE) as infile: 
    data = [line.rstrip().split('\t') for line in infile] 

data.sort(key=operator.itemgetter(0)) 

outfile=open(OUTPUT_FILE2,'w') 

for item in data: 
    last=item[0] 
    first=item[1] 
    start=item[2] 
    end=item[3] 

    outfile.write('%s %s was president from %s to %s\n' % (last,first,start,end)) 

メイン()

関連する問題