作者GreatDaiDai (DaiDai)
看板Python
标题[问题] 程式码问题
时间Mon Mar 16 13:56:06 2020
https://reurl.cc/yZgRXD
上面是用Python抓八卦版资讯,我不懂得是:
1.第29行有个articles = [] ,第71行也有个 articles = [],为什麽?如果都是要储存
文章,那第71行的 articles = []需要写吗?
2.def get_author_ids(posts, pattern):
ids = set()
for post in posts:
if pattern in post['author']:
ids.add(post['author'])
return ids
这边完全看不懂,而且跟前面那个抓作者的资料有关系吗?他之前不就写:
author = '' # author = d.find('div', 'author').text if d.find('div',
'author') else ''
那不就用#後面那行就好了?为什麽还要def get_author_ids这个函数?
请大大指教,感谢~~
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 117.56.12.220 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1584338168.A.F84.html
1F:→ darama: 1. variable scope不一样 03/16 14:47
2F:→ darama: 2. 他main有注解这个func的用途 你再看看吧 03/16 14:49
3F:→ DeepLearning: 爬文可以考虑 PyPtt 爬得比较快 03/16 17:57
5F:→ GreatDaiDai: 感谢!但我比较想用懂为什麽 03/16 20:11
6F:→ alvinlin: 1. 第29行是副程式,71是主程式 03/16 21:33
7F:→ alvinlin: 副程式的变数在副程式跑完就不存在了但它跑完前return给 03/16 21:35
8F:→ alvinlin: 主程式了 03/16 21:35
9F:→ alvinlin: 2.def get_author_ids 这个副程式用set 集合去累加,当 03/16 21:37
10F:→ alvinlin: 文章的作者里有特定字串的 03/16 21:37
11F:→ alvinlin: 但author = '' ,後面#已经被注释掉了 03/16 21:38
12F:→ alvinlin: 所以要看书里怎麽写。 03/16 21:38
13F:→ alvinlin: 其实这段code我在书里看过。 03/16 21:39
14F:→ alvinlin: 原书上的是没有# 的。所以如有照原书的意思, 5566那个 03/16 21:46
15F:→ alvinlin: 只是让你想去抓特定作者时用,但预设没有去抓 03/16 21:46
16F:→ alvinlin: 所以。照原书的code是有关系啊。就是去抓div里author的 03/16 21:48
17F:→ alvinlin: 字串,把不重复的作者全部列出来 03/16 21:48
18F:→ alvinlin: 补充1,所以,他们两只是刚好变数名相同。 03/16 21:49
19F:→ alvinlin: 去跑debug mode就看得出来了 03/16 21:49
20F:→ alvinlin: 所以。71行需要写啊,不然这个值不会写入档案 03/16 21:51
21F:→ alvinlin: 其实DeepLearning哥是专家,他哥CodingMan哥也是。 03/16 22:04
22F:→ alvinlin: 看起来是一本书里第三和第五章都用同样的副程式啦。有些 03/16 22:08
23F:→ alvinlin: 有被call有些没有。这不重要啦。 03/16 22:08
24F:→ alvinlin: 简单想看结果把副程式全部放回主程式一行一行跑就知道结 03/16 22:10
25F:→ alvinlin: 果了 03/16 22:10
26F:→ GreatDaiDai: 感谢A大!太详细了! 03/17 10:02
27F:→ alvinlin: ^^ 03/17 20:15