csv.writer 在单独的列/单元格中写入单词的每个字符 [英] csv.writer writing each character of word in separate column/cell

查看:25
本文介绍了csv.writer 在单独的列/单元格中写入单词的每个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目的:从models中所有行内的anchor标签中提取文本并将其放入csv中.

Objective: To extract the text from the anchor tag inside all lines in models and put it in a csv.

我正在尝试这个代码:

with open('Sprint_data.csv', 'ab') as csvfile:
  spamwriter = csv.writer(csvfile)
  models = soup.find_all('li' , {"class" : "phoneListing"})

  for model in models:

      model_name = unicode(u' '.join(model.a.stripped_strings)).encode('utf8').strip()
      spamwriter.writerow(unicode(u' '.join(model.a.stripped_strings)).encode('utf8').strip())

除了 csv 中的每个单元格只包含一个字符外,它工作正常.

It's working fine except each cell in the csv contains only one character.

像这样:

|  S  |  A  |   M  |   S  |   U   |  N  |   G   |

代替:

|SAMSUNG|

当然我错过了一些东西.但是什么?

Of course I'm missing something. But what?

推荐答案

writerow 接受一个序列.你给它一个单一的字符串,所以它把它当作一个序列,而字符串就像字符序列.

writerow accepts a sequence. You're giving it a single string, so it's treating that as a sequence, and strings act like sequences of characters.

在这一行你还想要什么?没有?如果是这样,请将其设为包含一项的列表:

What else do you want in this row? Nothing? If so, make it a list of one item:

spamwriter.writerow([u' '.join(model.a.stripped_strings).encode('utf8').strip()])

(顺便说一句,unicode() 调用是完全没有必要的,因为您已经加入了 unicode 分隔符.)

(By the way, the unicode() call is completely unnecessary since you're already joining with a unicode delimiter.)

这篇关于csv.writer 在单独的列/单元格中写入单词的每个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆