使用cs将结果写入.txt文件

2024-09-28 23:04:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要这个脚本的结果,即pygoogle搜索结果,如下所示:

name    # of results
name    # of results
name    # of results

以下是到目前为止我所掌握的,如何在不每次重新写入文件的情况下完成此操作:

^{pr2}$

运行脚本时,输出仅显示最近的一个,因为它正在重新编写脚本:


Tags: 文件ofname脚本情况resultspygooglepr2
3条回答

像这样:

>>> 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])

克服循环行为的困惑:

names变量将是一个列表,每次使用它时它只包含一个项。请执行以下操作:

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()) )

写一次文件

不覆盖以前的查询

您需要颠倒withfor语句的顺序,这将打开文件一次:

^{pr2}$

或者,在附加模式下打开文件:

for name in names:
    with open("output.txt", "a") as f:
        f.writelines(name)

在这种情况下,数据将在末尾添加。在

转换数据

为了得到你想要的东西而采取的步骤。在

  1. 将原始列表转换为单词列表。在
  2. 把名单分成两人一组。在
  3. 写出两对。在

具体如下:

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

要在不重写的情况下将追加写入文件,请将+添加到模式:

for name in names:
    with open("output.txt", "wb+") as f:
        writer = csv.writer(f)
        writer.writerows(A)

另一方面,为了提高效率,您可以只打开一次文件,并使用文件方法代替CSV模块:

^{pr2}$

相关问题 更多 >