数据结构化与保存

?
1
2
3
4
f = open ( 'content.txt' , 'a' , encoding = 'utf - 8' )
# content为文本正文
f.write(content)
f.close()

2. 将新闻数据结构化为字典的列表:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
news = {}
# 读取新闻细节
def getNewDetail(detail,title,description):
     resDescript = requests.get(detail,headers)
     resDescript.encoding = 'utf-8'
     soupDescript = BeautifulSoup(resDescript.text, 'html.parser' )
     news[ 'title' ] = soupDescript.select( '.show-title' )[ 0 ].text
 
     content = soupDescript.select( '.show-content' )[ 0 ].text  # 正文
     info = soupDescript.select( ".show-info" )[ 0 ].text  # info相关内容
     # 第一种方法 分离 message = info.split()
     # 第二种方法 用正则表达式
     print ( '标题' + ': ' + title)
     print ( '概要' + ': ' + description)
     print ( '链接' + ': ' + detail)
     print ( '正文' + ' :' + content)
     if (re.search( "发布时间:(.*) \xa0\xa0 \xa0\xa0作者:" , info) ! = 'Null' ):
         time = re.search( "发布时间:(.*) \xa0\xa0 \xa0\xa0作者:" , info).group( 1 )
         news[ 'time' ] = time
     else :news[ 'time' ] = "null"
     if (re.search( "作者:(.*)\xa0\xa0审核:" , info) ! = 'Null' ):
         author = re.search( "作者:(.*)\xa0\xa0审核:" , info).group( 1 )
         news[ 'author' ] = author
         print ( "作者:" + author)
     else :news[ 'author' ] = "null"
     if (re.search( "审核:(.*)\xa0\xa0来源:" , info) ! = 'Null' ):
         right = re.search( "审核:(.*)\xa0\xa0来源:" , info).group( 1 )
         news[ 'right' ] = right
     else :news[ 'right' ] = "null"
     if (re.search( '来源:(.*)\xa0\xa0\xa0\xa0摄影:' , info) ! = "null" ):
         resource = re.search( '来源:(.*)\xa0\xa0\xa0\xa0摄影:' , info)
         news[ 'resource' ] = resource
     else :news[ 'resource' ] = "null"
     if (re.search( "摄影:(.*)\xa0\xa0\xa0\xa0点击:" , info)! = "Null" ):
         video = re.search( "摄影:(.*)\xa0\xa0\xa0\xa0点击:" , info)
         news[ 'video' ] = video
     else :news[ 'video' ] = "null"
     count = getNewsId(detail)
     news[ 'count' ] = content
     dateTime = datetime.strptime(time, '%Y-%m-%d %H:%M:%S' )
     news[ 'dataTime' ] = dateTime

3. 安装pandas,用pandas.DataFrame(newstotal),创建一个DataFrame对象df.

df = pandas.DataFrame(all_news)

4. 通过df将提取的数据保存到csv或excel 文件。

?
1
df.to_excel( 'news.xlsx' )

5. 用pandas提供的函数和方法进行数据分析:

  • 提取包含点击次数、标题、来源的前6行数据
  • 提取‘学校综合办’发布的,‘点击次数’超过3000的新闻。
  • 提取'国际学院'和'学生工作处'发布的新闻。
?
1
2
3
4
df[[ 'clicks' , 'title' , 'source' ]].head( 6 )
df[(df[ 'clicks' ] > 3000 ) & (df[ 'source' ] = = '学校综合办' )]
news_info = [ '国际学院' , '学生工作处' ]
df[df[ 'source' ].isin(news_info)]

转载于:https://www.cnblogs.com/SOLARLKS/p/8810051.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值