<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Yukun&#039;s Blog &#187; Module</title>
	<atom:link href="http://www.yukun.info/blog/tag/module/feed" rel="self" type="application/rss+xml" />
	<link>http://www.yukun.info</link>
	<description>難しいことは分かりやすく、簡単なことは面白く紹介</description>
	<lastBuildDate>Thu, 26 Jan 2012 03:33:59 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Python: テキストファイルの行頭に行番号を追加</title>
		<link>http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html</link>
		<comments>http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html#comments</comments>
		<pubDate>Mon, 08 Sep 2008 12:50:42 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Command]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[read]]></category>
		<category><![CDATA[write]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1017</guid>
		<description><![CDATA[コマンドラインで指定されたテキストファイルの行頭に行番号を追加し、そのデータを新たなファイルに書き出すスクリプトです。 ソースコード #!/usr/bin/python # coding: UTF-8 import sy &#8230; <a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html">Python: テキストファイルの行頭に行番号を追加</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>コマンドラインで指定されたテキストファイルの行頭に行番号を追加し、そのデータを新たなファイルに書き出すスクリプトです。</p>
<h3>ソースコード</h3>
<pre>
#!/usr/bin/python
# coding: UTF-8

import sys

argvs = sys.argv
argc = len(argvs)
if (argc != 3):
    print 'Usage: $ python %s target_file making_file' % argvs[0]
    quit()
f = open(argvs[1])
lines2 = f.readlines()
f.close()
nf = open(argvs[2], 'w')
i = 1
for line in lines2:
    nf.write('%3d: %s' % (i, line))
    i = i + 1
nf.close()
</pre>
<p>仮にこのソースコードをfile05a.pyというファイルで保存した場合、使用する際はプロンプトに以下のように打ち込みます。</p>
<h3>実行結果</h3>
<h4>プロンプト</h4>
<pre>
> python file05a.py file05a.py file05a-l.txt
</pre>
<p>この結果、生成されたファイルが下記になります。</p>
<h4>file05a-l.txt</h4>
<pre>
  1: #!/usr/bin/python
  2: # coding: UTF-8
  3:
  4: import sys
  5:
  6: argvs = sys.argv
  7: argc = len(argvs)
  8: if (argc != 3):
  9:     print 'Usage: $ python %s target_file making_file' % argvs[0]
 10:     quit()
 11: f = open(argvs[1])
 12: lines2 = f.readlines()
 13: f.close()
 14: nf = open(argvs[2], 'w')
 15: i = 1
 16: for line in lines2:
 17:     nf.write('%3d: %s' % (i, line))
 18:     i = i + 1
 19: nf.close()
</pre>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html" rel="bookmark" title="2008年7月26日">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html" rel="bookmark" title="2008年9月6日">Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html" rel="bookmark" title="2008年9月18日">Python: ファイル読み込み時の例外の扱い例 &#8211; try、except、else、finallyブロック</a></li>
</ul>
<p><!-- Similar Posts took 12.648 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html">Python: テキストファイルの行頭に行番号を追加</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Python: コマンドライン引数の取得 &#8211; sys.argv変数</title>
		<link>http://www.yukun.info/blog/2008/07/python-command-line-arguments.html</link>
		<comments>http://www.yukun.info/blog/2008/07/python-command-line-arguments.html#comments</comments>
		<pubDate>Fri, 25 Jul 2008 15:00:55 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Command]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[read]]></category>

		<guid isPermaLink="false">http://trumpcode.yukun.info/?p=213</guid>
		<description><![CDATA[コマンドラインで与える引数によってプログラムの挙動を変えたいという場面はよくあります。Python ではコマンドライン引数は sys モジュールの argv 属性に文字列を要素とするリストとして格納されています。そして、 &#8230; <a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>コマンドラインで与える引数によってプログラムの挙動を変えたいという場面はよくあります。Python ではコマンドライン引数は <strong>sys モジュールの argv 属性に文字列を要素とするリスト</strong>として格納されています。そして、リストの先頭要素(sys.argv[0])はスクリプトファイル名となっています。</p>
<h2>ソースコード</h2>
<pre>
# coding: Shift_JIS

import sys # モジュール属性 argv を取得するため

argvs = sys.argv  # コマンドライン引数を格納したリストの取得
argc = len(argvs) # 引数の個数
# デバッグプリント
print argvs
print argc
print
if (argc != 2):   # 引数が足りない場合は、その旨を表示
    print 'Usage: # python %s filename' % argvs[0]
    quit()         # プログラムの終了

print 'The content of %s ...n' % argvs[1]
f = open(argvs[1])
line = f.readline() # 1行読み込む(改行文字も含まれる)
while line:
    print line
    line = f.readline()
f.close
</pre>
<h4>text.txt</h4>
<pre>
It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.
</pre>
<h2>実行結果</h2>
<h3>引数を指定しない場合</h3>
<pre>
$ python argv01.py
['argv01.py']
1

Usage: # python SCRIPTNAME.py filename
</pre>
<h3>引数を指定した場合</h3>
<pre>
$ python argv01.py text.txt
['argv01.py', 'text.txt']
2

The content of text.txt ...

It is meaningless only to think my long further aims idly.

It is important to set my aims but at the same time I should confirm my present condition.

Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.
</pre>
<h3>リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/tut/node12.html" title="10. Brief Tour of the Standard Library" target="_blank">10. Brief Tour of the Standard Library</a>
<ul>
<li><a href="http://docs.python.org/tut/node12.html#SECTION0012300000000000000000" title="10.3 Command Line Arguments" target="_blank">10.3 Command Line Arguments</a></li>
</ul>
</li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-file.html" rel="bookmark" title="2008年6月9日">Python: テキストファイルの読み込み &#8211; read()、readlines()、readline()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-read-file-try-except-else-finally.html" rel="bookmark" title="2008年9月18日">Python: ファイル読み込み時の例外の扱い例 &#8211; try、except、else、finallyブロック</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-file-write-writelines.html" rel="bookmark" title="2008年9月6日">Python: テキストファイルに書き込み &#8211; write()、writelines()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
</ul>
<p><!-- Similar Posts took 9.421 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/07/python-command-line-arguments.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Python: SQLiteにデータを格納、検索、出力 &#8211; pysqlite</title>
		<link>http://www.yukun.info/blog/2008/07/python-sqlite-insert.html</link>
		<comments>http://www.yukun.info/blog/2008/07/python-sqlite-insert.html#comments</comments>
		<pubDate>Sun, 13 Jul 2008 15:00:32 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://trumpcode.yukun.info/?p=136</guid>
		<description><![CDATA[レコードの検索や格納処理性能がオープンソースのDBで間に合う程度の問題であれば、積極的に使っていきたいです。それによって、他のロジックのコーディングに傾注できます。また、DBという共通のプラットフォームは複数言語から扱え &#8230; <a href="http://www.yukun.info/blog/2008/07/python-sqlite-insert.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/07/python-sqlite-insert.html">Python: SQLiteにデータを格納、検索、出力 &#8211; pysqlite</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>レコードの検索や格納処理性能がオープンソースのDBで間に合う程度の問題であれば、積極的に使っていきたいです。それによって、他のロジックのコーディングに傾注できます。また、DBという共通のプラットフォームは複数言語から扱えますので、データの再利用がしやすいです。<br />
さて、今回はPythonからSQLiteを扱うサンプル(pysqliteの使い方)を書いてみます。</p>
<h3>ソースコード</h3>
<pre>
# coding: UTF-8

from pysqlite2 import dbapi2 as sqlite

# データベースに接続(作成)
con = sqlite.connect('test1.db')
# テーブルの列要素: 名前、性別(male or female)、年齢
con.execute('CREATE TABLE people (name TEXT, sex TEXT, age INTEGER)')
# テストデータの挿入(1行はタプルで)
con.execute('INSERT INTO people VALUES ("Taro", "male", 22)')
con.execute('INSERT INTO people VALUES ("Hanako", "female", 38)')
con.execute('INSERT INTO people VALUES ("Ranka", "female", 17)')
con.execute('INSERT INTO people VALUES ("Ozuma", "male", 40)')
con.commit() # DBに反映

# データの検索
cur = con.execute('SELECT * FROM people')
# データの出力
print 'NAMEt  SEXt  AGE'
for row in cur:
    print '%-8s  %-6s  %2d' % row # 1行のデータ構造はタプル
con.close()
</pre>
<h3>実行結果</h3>
<pre>
NAME      SEX     AGE
Taro      male    22
Hanako    female  38
Ranka     female  17
Ozuma     male    40
</pre>
<h3>ドキュメント</h3>
<ul>
<li><a href="http://oss.itsystementwicklung.de/trac/pysqlite/" title="pysqlite – Trac" target="_blank">pysqlite – Trac</a></li>
<li><a href="http://oss.itsystementwicklung.de/download/pysqlite/doc/sqlite3.html" title="sqlite3 — DB-API 2.0 interface for SQLite databases — pysqlite Documentation" target="_blank">sqlite3 — DB-API 2.0 interface for SQLite databases — pysqlite Documentation</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/12/air-actionscript-sqlite-statement.html" rel="bookmark" title="2008年12月22日">AIR: SQLiteでデータの挿入と検索 &#8211; SQLConnection、SQLStatementクラス</a></li>
<li><a href="http://www.yukun.info/blog/2008/11/mysql-insert-into-table-values.html" rel="bookmark" title="2008年11月11日">MySQL: データをテーブルに追加 &#8211; INSERT文、INTO、VALUES句</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/mws-import-card.html" rel="bookmark" title="2008年6月23日">Magic Workstation にインポートするオリジナルカードの作成スクリプト</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/install-lxml.html" rel="bookmark" title="2008年6月13日">Python: lxmlのインストール方法</a></li>
</ul>
<p><!-- Similar Posts took 13.763 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/07/python-sqlite-insert.html">Python: SQLiteにデータを格納、検索、出力 &#8211; pysqlite</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/07/python-sqlite-insert.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Magic Workstation にインポートするオリジナルカードの作成スクリプト</title>
		<link>http://www.yukun.info/blog/2008/06/mws-import-card.html</link>
		<comments>http://www.yukun.info/blog/2008/06/mws-import-card.html#comments</comments>
		<pubDate>Sun, 22 Jun 2008 15:00:00 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Game]]></category>
		<category><![CDATA[Magic]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[MWS]]></category>

		<guid isPermaLink="false">http://www.yukun.info/trump/19700101/magic-workstation-%e3%81%ab%e3%82%a4%e3%83%b3%e3%83%9d%e3%83%bc%e3%83%88%e3%81%99%e3%82%8b%e3%82%ab%e3%83%bc%e3%83%89%e3%81%ae%e4%bd%9c%e6%88%90%e3%82%b9%e3%82%af%e3%83%aa%e3%83%97%e3%83%88</guid>
		<description><![CDATA[Magic Workstation(MWS)という対戦カードゲームMagic: The Gatheringが出来るソフトがありますが、その機能の一つにオリジナルカードのインポート機能があります。カードの作成方法はテキスト &#8230; <a href="http://www.yukun.info/blog/2008/06/mws-import-card.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/06/mws-import-card.html">Magic Workstation にインポートするオリジナルカードの作成スクリプト</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.magicworkstation.com/" target="_blank">Magic Workstation</a>(MWS)という対戦カードゲーム<a href="http://mtg.takaratomy.co.jp/" target="_blank">Magic: The Gathering</a>が出来るソフトがありますが、その機能の一つにオリジナルカードのインポート機能があります。カードの作成方法はテキストファイルに規定の書式で書いていけばいいのですが、自動化できるところがありましたので、即席ですがスクリプトを書いてみました。<br />
<a href="http://www.yukun.info/downloads/SpoilerMaker.py" title="MWSのオリジナルカード作成スクリプト">SpoilerMaker.py</a></p>
<h3>使い方</h3>
<p>コマンドラインの第1引数に後述に説明する書式で作成したファイル名、第2引数に変換した(MWS規定の書式)ファイルを書き込むファイル名を指定してください。</p>
<h4>使用例</h4>
<pre>
D:&#92;pytmp&#62;python SpoilerMaker.py sample_cards.txt converted_cards.txt
ファイル&#34;sample_cards.txt&#34;を読み込みます。
変換処理中...
変換処理が完了しました。
ファイル&#34;converted_cards.txt&#34;に変換データを保存しました。
</pre>
<h3>機能</h3>
<p>具体例を以って示しますと、以下のような書式のファイルをMWSの規定に合わせた書式に書き直します。</p>
<h4>読み込むファイル(作成するもの) sample_cards.txt</h4>
<pre>
CN Apothecary Initiate
CC W
MC W
TC Creature - Kithkin Cleric
PT 1/1
CT Whenever a player plays a white spell you may pay %1. If you do, you gain 1 life.
FT
AT
RA C
CA 1/3

CN Armored Ascension
CC W
MC 3W
TC Enchantment - Aura
PT
CT Enchant creature  Enchanted creature gets +1/+1 for each Plains you control and has flying.
FT
AT
RA U
CA 2/3

CN Ballynock Cohort
CC W
MC 2W
TC Creature - Kithkin Soldier
PT 2/2
CT First strike  Ballynock Cohort gets +1/+1 as long as you control another white creature.
FT A kithkin&#39;s worst enemy is solitude
AT Jesper Ejsing
RA C
CA 3/3
</pre>
<p>1枚のカードは空行で区切ります。行頭にCN, CC, MC, TC, PT, CT, FT, AT, RA, CAを書き、小スペースをあけて該当する属性を書きます。省略した項目は自動的に追加され、その項目の属性値は空文字で置換されます。ただし、カードナンバー(Card #:の欄に書くもの)は自動的に計算されたものが書き込まれます。</p>
<h4>書き出すファイル書式(MWSデフォルト規定)</h4>
<p>注:Webページ用に一部のタブ文字の数を調整しました。</p>
<pre>
Card Name:	Apothecary Initiate
Card Color:	W
Mana Cost:	W
Type &#38; Class:	Creature - Kithkin Cleric
Pow/Tou:	1/1
Card Text:	Whenever a player plays a white spell you may pay %1. If you do, you gain 1 life.
Flavor Text:
Artist:
Rarity:	C
Card #:	1/3

Card Name:	Armored Ascension
Card Color:	W
Mana Cost:	3W
Type &#38; Class:	Enchantment - Aura
Pow/Tou:
Card Text:	Enchant creature  Enchanted creature gets +1/+1 for each Plains you control and has flying.
Flavor Text:
Artist:
Rarity:	U
Card #:	2/3

Card Name:	Ballynock Cohort
Card Color:	W
Mana Cost:	2W
Type &#38; Class:	Creature - Kithkin Soldier
Pow/Tou:	2/2
Card Text:	First strike  Ballynock Cohort gets +1/+1 as long as you control another white creature.
Flavor Text:	A kithkin&#39;s worst enemy is solitude
Artist:	Jesper Ejsing
Rarity:	C
Card #:	3/3
</pre>
<h4>カード1枚のテンプレート</h4>
<pre>
CN
CC
MC
TC
PT
CT
FT
AT
RA
CA
</pre>
<h3>スクリプトを使用する利点</h3>
<ol>
<li>各項目が&#8221;CA&#8221;(Card Name項目)など2文字なので、打ち込みや修正が簡単。同時に、各項目の列が揃うので見栄えも良く管理しやすいかも。MWS側でも項目名は変更できますけれどね。</li>
<li>カードナンバー(Card #:の欄に書くもの)を自動的に計算してくれます。読み込みファイルのナンバーが正しくなくてもOKです。カードを任意の場所に挿入できて管理が楽かも。</li>
</ol>
<p>実装したい機能等がありましたらコメントやブクマコメント等で気軽にどうぞ。</p>
<p>一応コードを表示しておきます。</p>
<pre>
# coding: Shift_JIS

"""
Magic Work Station の Spoiler List 作成スクリプト
author  : Yukun
Edit    : 2008/6/23
GPLv2
"""

import sys

version = '0.1'

err_inv = 'SpoilerMaker\'s Error: Nonexistent key'
err_non = 'Nothing'
success = 'Normal'

class MagicCard:
    CN = 'Card Name:\t'
    CC = 'Card Color:\t'
    MC = 'Mana Cost:\t'
    TC = 'Type &#038; Class:\t'
    PT = 'Pow/Tou:\t'
    CT = 'Card Text:\t'
    FT = 'Flavor Text:\t'
    AT = 'Artist:\t\t'
    RA = 'Rarity:\t\t'
    CA = 'Card #:\t\t'

    def __init__(self):
        self.flag = 0
        self.attr = [{'CN':MagicCard.CN},
                    {'CC':MagicCard.CC},
                    {'MC':MagicCard.MC},
                    {'TC':MagicCard.TC},
                    {'PT':MagicCard.PT},
                    {'CT':MagicCard.CT},
                    {'FT':MagicCard.FT},
                    {'AT':MagicCard.AT},
                    {'RA':MagicCard.RA},
                    {'CA':MagicCard.CA},
                    ]

    def set_attr(self, key, value):
        attr = self.attr
        for i in range(len(attr)):
            if (attr[i].get(key, err_non) != err_non):
                attr[i][key] = attr[i][key]+value
                self.flag = 1
                self.attr = attr
                return success
        return err_inv

    def __str__(self):
        attr = self.attr
        str = ''
        for i in range(len(attr)):
            for (k, v) in attr[i].items():
                str += '%s :: %s\n' % (k, v)
        return str

class SpoilerMaker:
    def __init__(self):
        self.cards = []
        self.card_num = 0
        self.line_num = 0

    def read(self, filename):
        f = open(filename)
        x = f.read()
        f.close()
        lines = x.split('\n')

        cards = self.cards
        card = MagicCard()
        card_num = self.card_num
        line_num = self.line_num

        for line in lines:
            line_num +=1
            if (line == ''):
                if (card.flag != 0):
                    cards.append(card)
                    card_num += 1
                    card = MagicCard()
            else:
                kv = line.split(' ', 1)
                if (len(kv) != 2):
                    print '  %d行目でエラーです。書式を確認してください。' % line_num
                    print '  処理を中断し、終了します。'
                    exit(1)
                s = card.set_attr(kv[0], kv[1])
                if (s != success):
                    print '  %d行目でエラーです。書式を確認してください。' % line_num
                    print '  %s :: \'%s\' at line %d' % (s, kv[0], line_num)
        self.card_num = card_num
        self.line_num = line_num
        self.cards = cards

    def write(self, filename):
        g = open(filename, 'w')
        cards = self.cards
        for i in range(len(cards)):
            attr = cards[i].attr
            for j in range(len(attr)):
                if (j == 9):
                    attr[j]['CA'] = '%s%d/%d' % (MagicCard.CA, i+1, self.card_num)
                g.write('%s\n' % attr[j].values()[0])
            g.write('\n')
        g.close()

    def __str__(self):
        cards = self.cards
        str = ''
        for i in range(len(cards)):
            attr = cards[i].attr
            for j in range(len(attr)):
                str += '%s\n' % attr[j].values()[0]
            str += '\n'
        return str

def _main():
    argv_list = sys.argv
    readfile  = argv_list[1]
    writefile = argv_list[2]

    s = SpoilerMaker()
    print 'ファイル\"%s\"を読み込みます。' % readfile
    print '変換処理中...'
    s.read(readfile)
    print '変換処理が完了しました。'
    s.write(writefile)
    print 'ファイル\"%s\"に変換データを保存しました。' % writefile

if __name__ == '__main__': _main()
</pre>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/06/python-random.html" rel="bookmark" title="2008年6月10日">Python: 乱数の生成 &#8211; random()、randint()、uniform()、seed()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html" rel="bookmark" title="2008年7月26日">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-csv-read.html" rel="bookmark" title="2008年6月17日">Python: CSVファイルの読み込み &#8211; csv.readerオブジェクト</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-random2.html" rel="bookmark" title="2008年6月11日">Python: モジュールにテスト関数を定義 &#8211; 重複のない乱数(整数MIN以上MAX以下)の生成</a></li>
</ul>
<p><!-- Similar Posts took 11.396 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/06/mws-import-card.html">Magic Workstation にインポートするオリジナルカードの作成スクリプト</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/06/mws-import-card.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Python: lxmlのインストール方法</title>
		<link>http://www.yukun.info/blog/2008/06/install-lxml.html</link>
		<comments>http://www.yukun.info/blog/2008/06/install-lxml.html#comments</comments>
		<pubDate>Thu, 12 Jun 2008 15:00:00 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[Setting]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.yukun.info/trump/19700101/lxml%e3%81%ae%e3%82%a4%e3%83%b3%e3%82%b9%e3%83%88%e3%83%bc%e3%83%ab%e6%96%b9%e6%b3%95</guid>
		<description><![CDATA[lxml とはXMLやHTMLを扱うPythonのライブラリの一つです。 lxml is the most feature-rich and easy-to-use library for working with XM &#8230; <a href="http://www.yukun.info/blog/2008/06/install-lxml.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/06/install-lxml.html">Python: lxmlのインストール方法</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>lxml とはXMLやHTMLを扱うPythonのライブラリの一つです。</p>
<blockquote><p>lxml is the most feature-rich and easy-to-use library for working with XML and HTML in the Python language.<br />
 &#8211; <span style="font-style:italic;"><a href="http://codespeak.net/lxml/" target="_blank">lxml</a></span>の冒頭の文より</p></blockquote>
<h3>linux系OS(Fedoraなど)の場合</h3>
<pre>
# yum python-lxml
</pre>
<p>も一つの手ですがバージョンが古いので、通常はeasy_install経由でlxmlをインストールします。</p>
<p>前段階として、easy_installをインストールするために<a href="http://peak.telecommunity.com/dist/ez_setup.py" title="easy_installコマンドのインストール">http://peak.telecommunity.com/dist/ez_setup.py</a>をダウンロードしてスーパーユーザで実行します。</p>
<pre>
# python ez_setup.py error: invalid Python installation: unable to open /usr/lib/python2.5/config/Makefile (No such file or directory)
</pre>
<p>上のようなエラーがでた場合はpython-develをインストールします。また、合わせてlxmlに必要なパッケージもインストールするには以下のようなコマンドを実行します。</p>
<pre>
# yum install python-devel libxml2* libxslt*
</pre>
<p>改めて、</p>
<pre>
# python ez_setup.py
</pre>
<p>完了後、easy_installコマンドが実行できるようになります。<br />
lxmlのインストールは以下のコマンドを実行すればOKです。</p>
<pre>
# easy_install lxml
</pre>
<p>ライブラリの確認方法は、</p>
<pre>
$ python
>>> import lxml
>>>
</pre>
<p>でエラーが出なければOKです。</p>
<h3>アンインストール方法</h3>
<p>以下のコマンドを実行。</p>
<pre>
# easy_install -mxN lxml
</pre>
<h3>Windowsの場合</h3>
<p>Webアプリのデプロイ環境はLinux系だけれど、開発やテストの一部はWindows機で行いたいのでWindowsにeasy_installでインストールしようとしましたが、途中でエラーが出て中々上手くいきませんでした。</p>
<p>解決に時間が掛かりそうだったので、とりあえず<a href="http://pypi.python.org/pypi/lxml/1.3.4">Python Package Index : lxml 1.3.4</a>のlxml-1.3.4.win32-py2.5.exeをダウンロード＆インストールして済ませました。</p>
<h3>参考にした記事</h3>
<ul>
<li><a href="http://d.hatena.ne.jp/kuma8/20070712/1184247598" target="_blank">lxmlがインストールできない &#8211; kuma8の日記</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2011/03/python-twitter-install.html" rel="bookmark" title="2011年3月5日">Python Twitter のインストール</a></li>
<li><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html" rel="bookmark" title="2008年7月26日">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/fedora-yum-install-gnome.html" rel="bookmark" title="2008年9月15日">FedoraにGUI環境GNOMEをyumでインストール</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/python-add-line-number-to-text-file.html" rel="bookmark" title="2008年9月8日">Python: テキストファイルの行頭に行番号を追加</a></li>
<li><a href="http://www.yukun.info/blog/2010/03/java-install-sen-windows.html" rel="bookmark" title="2010年3月25日">Java: 形態素解析Senをインストール(Windows編)</a></li>
</ul>
<p><!-- Similar Posts took 8.942 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/06/install-lxml.html">Python: lxmlのインストール方法</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/06/install-lxml.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python: モジュールにテスト関数を定義 &#8211; 重複のない乱数(整数MIN以上MAX以下)の生成</title>
		<link>http://www.yukun.info/blog/2008/06/python-random2.html</link>
		<comments>http://www.yukun.info/blog/2008/06/python-random2.html#comments</comments>
		<pubDate>Tue, 10 Jun 2008 15:00:00 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Exception]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[Number]]></category>
		<category><![CDATA[Random]]></category>

		<guid isPermaLink="false">http://www.yukun.info/trump/19700101/python-%e3%83%a2%e3%82%b8%e3%83%a5%e3%83%bc%e3%83%ab%e3%81%ab%e3%83%86%e3%82%b9%e3%83%88%e9%96%a2%e6%95%b0%e3%82%92%e5%ae%9a%e7%be%a9-%e9%87%8d%e8%a4%87%e3%81%ae%e3%81%aa%e3%81%84%e4%b9%b1%e6%95%b0</guid>
		<description><![CDATA[ソースコード #!/usr/bin/python # coding: UTF-8 import random def make_randint_list(min, max, cnt, sortflag=False, re &#8230; <a href="http://www.yukun.info/blog/2008/06/python-random2.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/06/python-random2.html">Python: モジュールにテスト関数を定義 &#8211; 重複のない乱数(整数MIN以上MAX以下)の生成</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<h3>ソースコード</h3>
<pre>
#!/usr/bin/python
# coding: UTF-8

import random

def make_randint_list(min, max, cnt, sortflag=False, revflag=False):
    """
    重複のない乱数(整数min以上max以下)を要素としたリストを返す
    """
    list = []
    i = 0
    while cnt != i:
        r = random.randint(min, max)
        try:
            list.index(r)   # 既にリストに存在するか
        except ValueError, e:
            list.append(r)  # 無い場合はリストに格納
            i = i + 1
    if (sortflag): list.sort(reverse=revflag)
    return list

def _main():
    """モジュールのチェック関数"""

    print 'makerand0.py [_main()]'
    print make_randint_list(10, 99, 10)
    print make_randint_list(10, 99, 10, True)       # 昇順ソート
    print make_randint_list(10, 99, 10, True, True) # 降順ソート

if __name__ == '__main__' : _main()
#
</pre>
<p>モジュール変数__name__の中には通常はモジュール名が入っています。しかし、このモジュールファイルを直接実行した場合は__name__に&#8217;__main__&#8217;という名前が入ります。その為、if __name__ == &#8216;__main__&#8217; : は真となり_main()が実行されます。</p>
<h3> 実行結果</h3>
<pre>
$ python makerand0.py
makerand0.py &#91;_main()]
&#91;62, 18, 55, 44, 97, 67, 87, 16, 59, 43]
&#91;11, 13, 30, 42, 46, 52, 71, 75, 81, 92]
&#91;88, 81, 65, 60, 57, 53, 41, 34, 27, 23]
</pre>
<h3> モジュールテスト用スクリプト</h3>
<h4> makerand0_test.py</h4>
<p>[py]<br />
#!/usr/bin/python<br />
# coding: UTF-8</p>
<p>from makerand import make_randint_list</p>
<p>print make_randint_list(10, 99, 10)<br />
print make_randint_list(10, 99, 10, True)<br />
print make_randint_list(10, 99, 10, True, True)<br />
[/py]</p>
<h3>実行結果</h3>
<pre>
$ python makerand0_test.py
&#91;52, 44, 63, 61, 50, 66, 88, 45, 99, 57]
&#91;15, 26, 29, 53, 56, 69, 89, 91, 94, 95]
&#91;96, 95, 93, 88, 79, 75, 64, 62, 33, 11]
</pre>
<h3> リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/lib/typesseq-mutable.html" target="_blank">3.6.4 Mutable Sequence Types</a></li>
<li><a href="http://docs.python.org/lib/module-random.html" target="_blank">6.4 random &#8212; Generate pseudo-random numbers</a></li>
<li><a href="http://docs.python.org/lib/inspect-types.html" target="_blank">26.10.1 Types and members</a></li>
</ul>
<h3> チュートリアル</h3>
<ul>
<li><a href="http://docs.python.org/tut/node8.html" target="_blank">6. Modules</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/06/python-random.html" rel="bookmark" title="2008年6月10日">Python: 乱数の生成 &#8211; random()、randint()、uniform()、seed()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/07/python-command-line-arguments.html" rel="bookmark" title="2008年7月26日">Python: コマンドライン引数の取得 &#8211; sys.argv変数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-list.html" rel="bookmark" title="2008年6月1日">Python: リストの初期化・出力・代入・要素数</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/r-draw-histogram.html" rel="bookmark" title="2008年9月9日">Rで統計: ヒストグラムの描画 &#8211; hist()関数</a></li>
<li><a href="http://www.yukun.info/blog/2008/08/python-if-for-in.html" rel="bookmark" title="2008年8月2日">Python: if/for文でのin演算子の各オブジェクト毎の評価</a></li>
</ul>
<p><!-- Similar Posts took 7.237 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/06/python-random2.html">Python: モジュールにテスト関数を定義 &#8211; 重複のない乱数(整数MIN以上MAX以下)の生成</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/06/python-random2.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python: 乱数の生成 &#8211; random()、randint()、uniform()、seed()メソッド</title>
		<link>http://www.yukun.info/blog/2008/06/python-random.html</link>
		<comments>http://www.yukun.info/blog/2008/06/python-random.html#comments</comments>
		<pubDate>Mon, 09 Jun 2008 15:00:00 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[Number]]></category>
		<category><![CDATA[Random]]></category>

		<guid isPermaLink="false">http://www.yukun.info/trump/19700101/python-%e4%b9%b1%e6%95%b0%e3%81%ae%e7%94%9f%e6%88%90-random%e3%80%81randint%e3%80%81uniform%e3%80%81seed%e3%83%a1%e3%82%bd%e3%83%83%e3%83%89%e3%81%ae%e4%bd%bf%e3%81%84%e6%96%b9</guid>
		<description><![CDATA[ソースコード #!/usr/bin/python # coding: UTF-8 # 乱数の生成 &#124; random()、randint()、uniform()、seed()メソッドの使い方 import random # &#8230; <a href="http://www.yukun.info/blog/2008/06/python-random.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2008/06/python-random.html">Python: 乱数の生成 &#8211; random()、randint()、uniform()、seed()メソッド</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<h3>ソースコード</h3>
<pre>
#!/usr/bin/python
# coding: UTF-8

# 乱数の生成 | random()、randint()、uniform()、seed()メソッドの使い方

import random # モジュールのインポート

print random.random(), 'n' # 0.0 ≦ F ＜ 1.0 の浮動小数点数をランダムに返す

# randint(x, y)メソッド: 整数x以上y以下(x ≦ N ≦ y)の乱数を返す
for i in range(10):
    print random.randint(10, 20), ' ',
print 'n'

# uniform(x, y)メソッド: 実数x以上y未満(x ≦ N ＜ y)の乱数を返す
for i in range(10):
    print random.uniform(10, 20)
print

# seed()メソッド: 乱数の種の初期化
#                 (省略した場合はシステムの現在時刻で初期化が行われる)
random.seed(1)  # 明示的に初期化
for i in range(10):
    print random.randint(10, 20), ' ',
print 'n'

random.seed(1)  # もう一度初期化(結果は上と同じとなる)
for i in range(10):
    print random.randint(10, 20), ' ',
print 'n'
</pre>
<h3>実行結果</h3>
<pre>
0.610071743263

16   16   15   11   19   16   10   11   20   18

12.8745815718
10.3223430071
10.9674507421
17.5459589302
16.0796539779
15.0854025011
18.6344006559
11.049275088
16.6396732404
12.0720922586

11   19   18   12   15   14   17   18   11   10

11   19   18   12   15   14   17   18   11   10
</pre>
<h3> リファレンス</h3>
<ul>
<li><a href="http://docs.python.org/lib/module-random.html" target="_blank">6.4 random &#8212; Generate pseudo-random numbers</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/06/python-random2.html" rel="bookmark" title="2008年6月11日">Python: モジュールにテスト関数を定義 &#8211; 重複のない乱数(整数MIN以上MAX以下)の生成</a></li>
<li><a href="http://www.yukun.info/blog/2008/01/cpp-random.html" rel="bookmark" title="2008年1月1日">C++でMIN以上MAX未満の乱数を生成</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/r-draw-histogram.html" rel="bookmark" title="2008年9月9日">Rで統計: ヒストグラムの描画 &#8211; hist()関数</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/python-dict2.html" rel="bookmark" title="2008年6月4日">Python: 辞書の全てのキーと値をたどる &#8211; items(), keys(), values()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2009/06/excel-vba-random-rnd-cells.html" rel="bookmark" title="2009年6月8日">Excel VBA: 指定した行、列内のテーブルのセルに乱数を格納</a></li>
</ul>
<p><!-- Similar Posts took 7.453 ms --></p>
<p><a href="http://www.yukun.info/blog/2008/06/python-random.html">Python: 乱数の生成 &#8211; random()、randint()、uniform()、seed()メソッド</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2008/06/python-random.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

