我想将数组导出为CSV文件

时间:2019-05-27 15:16:38

标签: python csv

我想用逗号或制表符分隔数组(1)和数组(2) 但 按每个字母分类。

现在

T,h,i,s,,i,s,,p,r,o,b,a,b,l,y,,t,h,e,,h,i,g,h,e ,s,t,,8,/,1,0,,I,,c,o,u,l,d,,g,i,v,e,,f,o,r,,a,n,, 8,/,1,0,,m,o,v,i,e,。,T,h,e,r,e ,, a,r,e,,s,o,m,e,,v, e,r,y,,g,o,o,d,,m,o,m,e,n,t,s,,i,n,,E,n,d,g,a,m,e, ,a,n,d,,t,h,a,t,',s ,, c,o,m,i,n,g,,f,r,o,m,,a,,l,o, n,g,,s,t,a,n,d,i,n,g,,M,C,U,,f,a,n,,g,r,o,w,i,n,g, ,u,p,,w,i,t,h,,t,h,e,s,e ,, m,o,v,i,e,s,。,,I,n,,c,r, e,a,t,i,n,g,,a,n,,e,x,t,e,n,s,i,v,e,,a,n,d,e,m,o, t,i,o,n,a,l,,j,o,u,r,n,e,y,,f,o,r,,a,,l,o,t,,o,f,, t,h,e,,M,C,U,,c,h,a,r,a,c,t,e,r,s,“,”,,i,t,,a,b,s, o,l,u,t,e,l,y ,, s,u,c,c,e,e,d,s,。,E,n,d,g,a,m,e,,u, l,t,i,m,a,t,e,l,y,,i,s,,a,n,e,x,c,e,l,l,e,n,t,,c, o,n,c,l,u,s,i,o,n,,t,o,,o,v,e,r,,1,0,,y,e,a,r,s,,o ,f,,f,i,l,m,,b,u,t,,I,,f,e,e,l,,t,h,e,,p,l,o,t,',s ,,p,a,c,i,n,g,,a,n,d,,d,i,r,e,c,t,i,o,n,,i,s,,r,e, a,l,l,y,,l,a,c,k,i,n,g,,t,o,I,n,f,i,n,i,t,y,,W,a, r,“,” ,, w,h,i,c,h ,,',t,r,i,m,m,e,d ,, t,h,e ,, f,a,t,', ,a,n,d ,, w,a,s ,, m,u,c,h ,, m,o,r,e ,, f,o,c,u,s,e,d, n,d,,e,n,e,r,g ,e,t,i,c,。,,G,r,a,n,t,e,d,

想要

[句子A],[句子B],[句子C]

html = driver.page_source
soup = BeautifulSoup(html, "html.parser")

for link in soup.find_all('div','text show-more__control'):
    Result.append(link.text.strip())



with open("Filename", 'w', encoding='utf-8')as f:
    writer = csv.writer(f)

    for i in range(len(Result)):
        row = Result[i]
        writer.writerow(row)



#Result is separated into String type.
#Result [1] = "sentence A"
#Result [2] = "sentence B"

谢谢!

1 个答案:

答案 0 :(得分:0)

例如,运行此代码

for link in soup.find_all('div','text show-more__control'):
    Result.append(link.text.strip())

向我们提供此列表(Result):

['foo', 'bar', 'baz']

现在让我们遍历列表

for i in range(len(Result)):
    row = Result[i]

row等同于列表中的每个元素:

  • 在第一次迭代中,它是'foo'
  • 在第二次迭代中,它是“ bar”
  • 在第三次迭代中是'baz'

每个值都是一个 string

在行

writer.writerow(row)

writerow方法需要一个可迭代的对象,并将可迭代的每个项目分配给csv行中的单独列。因此,如果将其传递给'foo',则结果行将为'f,o,o'。

如果只有一列-每行Result中的元素,则代码需要像这样:

with open("Filename", 'w', encoding='utf-8')as f:
    writer = csv.writer(f)

    for row in Result:
        writer.writerow([row])

我们将row设为长度为1的列表元素,以使writerow的行为符合预期。