我使用print语句后从网页中提取的数据如下所示。
[[u'Neoplasms', u'Medical Subject Headings', u'direct', u'cancer', u'Neoplasms', u'Medical Subject Headings', u'Malignant Neoplasm', u'National Cancer Institute Thesaurus', u'direct', u'cancer', u'Malignant Neoplasm', u'National Cancer Institute Thesaurus']]
我想把它写成这样的csv文件,每行包含六个元素。
Neoplasms, Medical Subject Headings, direct, cancer, Neoplasms, Medical Subject Headings
Malignant Neoplasm, National Cancer Institute Thesaurus, direct, cancer, Malignant Neoplasm, National Cancer Institute Thesaurus
请建议我如何做到这一点。
答案 0 :(得分:1)
在python 2.7中,您可以执行以下操作:
import csv
data = [[u'Neoplasms', u'Medical Subject Headings', u'direct', u'cancer', u'Neoplasms', u'Medical Subject Headings', u'Malignant Neoplasm', u'National Cancer Institute Thesaurus', u'direct', u'cancer', u'Malignant Neoplasm', u'National Cancer Institute Thesaurus']]
with open('out.csv', 'wb') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerows(data)
更新
要获取输入数据的六个元素块:可以使用此anwser中的以下函数:
def chunks(l, n):
""" Yield successive n-sized chunks from l. """
for i in xrange(0, len(l), n):
yield l[i:i+n]
然后要编写块,您可以使用:
with open('out.csv', 'wb') as csvfile:
csvwriter = csv.writer(csvfile)
for a_chunk in chunks(data[0], 6):
csvwriter.writerow(a_chunk)
请注意,目前尚不清楚输入数据是多个列表的列表,还是只有一个列表嵌入其他列表中。我假设了后者。