为什么csvwriter.writerow()在每个字符后放一个逗号? [英] Why does csvwriter.writerow() put a comma after each character?
问题描述
此代码打开网址,并在末尾添加 / names
并打开网页并将字符串打印到 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 bios in bios:
OpenThisLink = url + l
response = urllib2.urlopen(OpenThisLink)
html = response.read()
item = re.search('(JD)(。*?)(\d +)',html)
如果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, $ c>
如果我将字符串更改为(JD,哥伦比亚法学院....),那么我得到
JD,哥伦比亚法学院...)
我找不到文档如何指定delimeter。
如果我尝试使用 delimenter
,我会收到此错误:
TypeError:'delimeter'是此函数的无效关键字参数
感谢您的帮助。
它需要一个序列(例如:列表或元组)你给它一个字符串。一个字符串也是一个字符串序列,但它是一个1字符的字符串序列,这不是你想要的。
如果你只想要一个字符串您可以这样做:
csvwriter.writerow([JD])
这会用一个列表包装JD(一个字符串)。
This code opens the url and appends the
/names
at the end and opens the page and prints the string totest1.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)
But I get this result:
J,D,",", ,C,o,l,u,m,b,i,a, ,L,a,w, ,S,c,h,o,o,l,....
If I change the string to ("JD", "Columbia Law School" ....) then I get
JD, Columbia Law School...)
I couldn't find in the documentation how to specify the delimeter.
If I try to use
delimenter
I get this error:TypeError: 'delimeter' is an invalid keyword argument for this function
Thanks for the help.
解决方案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])
This wraps JD (a string) with a list.
这篇关于为什么csvwriter.writerow()在每个字符后放一个逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!