2012-02-28 22 views
1

私はPythonで単純なテーブルを印刷しようとしていますが、これまでの回答はまったく私が探しているものではありません。すべての助けが大いに感謝されるでしょう。Pythonでテーブルを印刷

私が(文章の)リストを持っている:

texts = [caesar,hamlet,macbeth,emma,persuasion,sense] 

私はその後、2つのテキストを比較し '類似性、' と呼ばれる機能を実行します。私はテーブルの結果を印刷したいと思いますが、printステートメントがリストの1つのループを反復した後に新しい行を得ることはできません。 [注:私は自然言語ツールキット、言語学のためのPythonモジュールを使用していますので、私は、Python 2.6.6を使用しています]

ここでは正しく動作しません。私の現在のprint文、次のとおりです。

for x in texts: 
    for y in texts: 
     print round(similarity(x,y),2), 
     if texts.index(x) == len(texts): 
      print '\n' 

正しい方向のポインタがあれば大丈夫です!

答えて

1

printを単独で使用してください。

また、なぜこのようなことをしていないのですか?

for x in texts: 
    for y in texts: 
     print round(similarity(x,y),2), 
    print 
1

単に外側のループに新しい行を印刷移動:

for x in texts: 
    for y in texts: 
     print "{:8.2f}".format(similarity(x,y)), 
    print 

print文は改行を出力します。また、round()は、文字列の書式設定には使用されません。代わりにstr.format()を使用してください。

+0

本当にありがとうございました。ほんとうにありがとう!私はsimilarity()関数が浮動小数点を出力するので、round()を使用しています。 –

+0

@Adam_G:なぜあなたは 'round()'を使用しているのか分かりますが、上記のように、 'round()'は出力フォーマットには使用されません。出力フォーマットの詳細については、Pythonチュートリアルの[Fancier Output Formatting](http://docs.python.org/tutorial/inputoutput.html#fancier-output-formatting)のセクションを参照してください。[浮動小数点演算:Issues and Limitations](http://docs.python.org/tutorial/floatingpoint.html)を参照してください。なぜなら、この目的のために 'round() 'を使うのは悪い考えです。 –

2

の各項目(別の又は同一の)リストをリスト内の各アイテムを比較する処理は、数学的Cartesian productとして知られています。 Pythonはこれを行うための組み込み機能を有する:itertools.productためのループネストに相当する:

と仮定AとBがリストである:

for x in A: 
    for y in B: 
     print (x,y) 

はとしてgenerator expressionと書くことができます。

for pair in ((x,y) for x in A for y in B): 
    print pair 

または、より簡潔に:

from itertools import product 
for pair in product(A, B): 
    print pair 

あなたのケースでは、あなたがしていますリストのすべての項目をそれ自身と比較すると、product(texts, texts)と書くことができますが、この場合、商品にはオプションのキーワード引数repeatがあります。product(A, repeat=4)product(A, A, A, A)と同じ意味です。

あなたはこのように今、あなたのコードを書き換えることができます:

from itertools import product 

caesar = """BOOK I 
I.--All Gaul is divided into three parts, one of which the Belgae 
inhabit, the Aquitani another, those who in their own language are 
called Celts, in ours Gauls, the third. All these differ from each other 
in language, customs and laws.""" 

hamlet = """Who's there?" 
"Nay, answer me. Stand and unfold yourself." 
"Long live the King!" 
"Barnardo!" 
"He." (I.i.1-5)""" 

macbeth = """ACT I SCENE I  A desert place. Thunder and lightning. 
[Thunder and lightning. Enter three Witches] 
First Witch When shall we three meet again 
In thunder, lightning, or in rain? 
Second Witch When the hurlyburly's done, 
When the battle's lost and won.""" 

texts = [caesar, hamlet, macbeth] 

def similarity(x, y): 
    """similarity based on length of the text, 
    substitute with similarity function from Natural Language Toolkit""" 
    return float(len(x))/len(y) 


for pair in product(texts, repeat=2): 
    print "{}".format(similarity(*pair))