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

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

问题描述

目的:要从models中所有行内的定位标记中提取文本,并将其放入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天全站免登陆