>>> import csv
>>> A = ["blah blah", "blah blah", "blah", "list"]
>>> lis = [y for x in A for y in x.split()]
>>> lis
['blah', 'blah', 'blah', 'blah', 'blah', 'list']
>>> it = iter(lis)
>>> with open("output.csv", "wb") as f:
writer = csv.writer(f, delimiter=' ')
writer.writerows([ [x,next(it)] for x in it])
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和for语句的顺序,这将打开文件一次:
^{pr2}$
或者,在附加模式下打开文件:
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)
像这样:
克服循环行为的困惑:
names
变量将是一个列表,每次使用它时它只包含一个项。请执行以下操作:写一次文件
不覆盖以前的查询
您需要颠倒
^{pr2}$with
和for
语句的顺序,这将打开文件一次:或者,在附加模式下打开文件:
在这种情况下,数据将在末尾添加。在
转换数据
为了得到你想要的东西而采取的步骤。在
具体如下:
更简洁地写为:
以正确的格式写出
如果不希望在输出中使用逗号,只需为
csvwriter
定义一个自定义方言:这就给了你想要的:
要在不重写的情况下将追加写入文件,请将
+
添加到模式:另一方面,为了提高效率,您可以只打开一次文件,并使用文件方法代替CSV模块:
^{pr2}$相关问题 更多 >
编程相关推荐