为什么 csvwriter.writerow() 在每个字符后放一个逗号? [英] Why does csvwriter.writerow() put a comma after each character?

查看:50
本文介绍了为什么 csvwriter.writerow() 在每个字符后放一个逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码打开 URL 并在末尾附加 /names 并打开页面并将字符串打印到 test1.csv:

This code opens the URL and appends the /names at the end and opens the page and prints the string to test1.csv:

import urllib2
import re
import csv

url = ("http://www.example.com")
bios = [u'/name1', u'/name2', u'/name3']
csvwriter = csv.writer(open("/test1.csv", "a"))

for l in bios:
    OpenThisLink = url + l
    response = urllib2.urlopen(OpenThisLink)
    html = response.read()
    item = re.search('(JD)(.*?)(d+)', html)
    if item:
        JD = item.group()
        csvwriter.writerow(JD)
    else:
        NoJD = "NoJD"
        csvwriter.writerow(NoJD)

但我得到了这个结果:

J,D,",", ,C,o,l,u,m,b,i,a, ,L,a,w, ,S,c,h,o,o,l,....

如果我将字符串更改为 ("JD", "Columbia Law School" ....) 然后我得到

If I change the string to ("JD", "Columbia Law School" ....) then I get

法学博士,哥伦比亚法学院...)

我在文档中找不到如何指定分隔符.

I couldn't find in the documentation how to specify the delimeter.

如果我尝试使用 delimeter 我得到这个错误:

If I try to use delimeter I get this error:

TypeError: 'delimeter' is an invalid keyword argument for this function

推荐答案

它需要一个字符串序列(例如:列表或元组).你给它一个字符串.一个字符串恰好也是一个字符串序列,但它是一个1个字符串的序列,这不是你想要的.

It expects a sequence (eg: a list or tuple) of strings. You're giving it a single string. A string happens to be a sequence of strings too, but it's a sequence of 1 character strings, which isn't what you want.

如果你只想要每行一个字符串,你可以这样做:

If you just want one string per row you could do something like this:

csvwriter.writerow([JD])

这用一个列表包装了 JD(一个字符串).

This wraps JD (a string) with a list.

这篇关于为什么 csvwriter.writerow() 在每个字符后放一个逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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