(给 抠腚男孩 加星标,提升Python技能 )
怎么一个个读出来呢?只能写
正则分组一一提取了,一两次还好,以后每次爬数据读取都要写一次,想想就令人害怕。 一种简单的方法就是,在存储时,用特定的结构,加入分隔符,如使用
CSV
作者:CoderPig在前面的章节中,我们对爬取到的数据进行解析,然后按照特定的规则,保存到txt文件中。存是挺好存的,但取就未必了,比如上一节《Python爬虫 | 0xb - 数据解析:PyQuery库》中保存的cites.txt文件:
![d5bd58d01c33acd866b1d8af90f8934f.png](https://i-blog.csdnimg.cn/blog_migrate/9978b2db5bac85e18b488e2bd3d40bb8.png)
-
分隔:
东京-Tokyo-封面-详情-0人去过-经典
提取的话,按行读取,调用下string的split('-')函数分组,按照游标一一对应即可。
![5cc597320269f4c85f2eeaba14fac569.png](https://i-blog.csdnimg.cn/blog_migrate/8d2b6091e0354525b949c499fa627157.png)
// 0x1、简介 //
CSV(Comma-Separated Values,逗号分隔值) 以纯文本形式存储表格数据(数字和文本), 记录间以某种换行符分隔。 跟我们上面用-
作为分隔符保存数据非常类似,CSV文件除了可以用普通文本编辑工具打开外,还可使用Excel打开。 Python中内置一个csv模块供我们处理CSV文件。
// 0x2、csv模块使用代码示例 //
# -*- coding: utf-8 -*-# !/usr/bin/env python"""------------------------------------------------- File : csv_test.py Author : CoderPig date : 2020-12-11 8:41 Desc : csv库使用代码示例-------------------------------------------------"""import csvimport os
save_file_name_first = os.path.join(os.getcwd(), '1.csv')
save_file_name_second = os.path.join(os.getcwd(), '2.csv')
save_file_name_third = os.path.join(os.getcwd(), '3.csv')
data_list = [
['id', 'name', 'age', 'kind'],
['1', 'CoderPig', '27', 'Android'],
['2', 'CodingBoy', '18', 'Python'],
['3', 'CodingGirl', '25', 'UI'],
]
data_list_headers = ['id', 'name', 'age', 'kind']
data_list_dict = [
{
'id': '1', 'name': 'CoderPig', 'age': '27', 'kind': 'Android'},
{
'id': '2', 'name': 'CodingBoy', 'age': '18', 'kind': 'Python'},
{
'id': '3', 'name': 'CodingGirl', 'age': '25', 'kind': 'UI'}
]# 不设置newline=''的话,每写入一行将会写入一个空行~# writerow → 单行写入def write_line(file_path):with open(file_path, 'w+', newline='') as f:
writer = csv.writer(f)for row in data_list:
writer.writerow(row)# writerows → 多行写入def write_lines(file_path):with open(file_path, 'w+', newline='') as f:
writer = csv.writer(f)
writer.writerows(data_list)# DictWriter → 字典写入def dict_writer_write(file_path):with open(file_path, 'w+', newline='') as f:
writer = csv.DictWriter(f, data_list_headers)
writer.writeheader()for row in