ループ動作に関する混乱を克服する:
変数は、names
使用するたびに項目が 1 つだけのリストになります。代わりにこれを行います:
import re
import csv
from pygoogle import pygoogle
names = []
with open('parse2.txt') as fin:
names = [x.strip() for x in fin.read().strip('\'"[]').split(' '*6)]
with open("output.txt") as fout:
for name in names:
g = pygoogle(name)
g.pages = 1
if (g.get_result_count()) == 0:
print "[Error]: could find no result for '{}'".format(name)
else:
fout.write("{} {} results\n".format(name, g.get_result_count()) )
ファイルを一度書き出す
以前のクエリを上書きせずに
with
andステートメントの順序を逆にする必要がありfor
ます。これにより、ファイルが一度開きます。
with open("output.txt", "wb+") as f:
for line in lines:
# Stuff...
for name in names:
f.writelines(name)
または、追加モードでファイルを開きます。
for name in names:
with open("output.txt", "a") as f:
f.writelines(name)
その場合、データは最後に追加されます。
データの変換
欲しいものを手に入れるためのステップ。
- 元のリストを単語のリストに変換します。
- リストをペアにグループ化します。
- ペアを書き出します。
次のように:
import re
from itertools import *
A = ["blah blah", "blah blah", "blah", "list"]
#
# from itertools doc page
#
def flatten(listOfLists):
"Flatten one level of nesting"
return list(chain.from_iterable(listOfLists))
def pairwise(t):
it = iter(t)
return izip(it,it)
#
# Transform data
#
list_of_lists = [re.split("[ ,]", item) for item in A]
# [['blah', 'blah'], ['blah', 'blah'], ['blah'], ['list']]
a_words = flatten(list_of_lists)
a_pairs = pairwise(a_words)
with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(a_pairs)
より簡潔に書くと次のようになります。
A_pairs = pairwise(flatten([re.split("[ ,]", item) for item in A]))
with open("output.csv", "wb") as f:
csv.writer(f).writerows(A_pairs)
適切な形式で書き出す
出力にカンマが必要ない場合は、次のようにカスタム方言を定義するだけですcsvwriter
。
>>> csv.register_dialect('mydialect', delimiter=' ', quoting=csv.QUOTE_MINIMAL)
>>> csv.writer(open("try.csv", "w"), dialect="mydialect").writerows(a_ps)
あなたが望むものを与える:
➤ cat try.csv
blah blah
blah blah
blah list