在此之前已经参加过两期打卡营了,第二期CV特辑的适合深感自己半路出家基础太不牢靠了,PaddlePaddle是我第二个使用的深度学习框架,以前看过一些pytorch。之前两期主要使用paddlepaddle搭建网络,没有详细了解深度学习使用时就特别难,这期的paddlehub不一样,简单易用,搭建快速,只要懂python基础,看着官方文档,马上就可以搞出来一个高大上的人工智能来。
参与前有些担心因为自己基本功不扎实,怕自己跟不上。但是参与之后发现,老师助教班班真的太棒了
day01
学习的是python基础,简单的循环和文件操作。比较难的一点就是文件操作(现在回头再看,也不是那么难),因为当时不知道有 os.walk()这个方法只能“苦兮兮”的自己写。
# 递归版本
def findfiles(path):
#在这里写下您的查找文件代码吧!
directory = os.listdir(path)
for one in directory:
f = os.path.join(path,one)
if os.path.isdir(f): #递归搜索文件夹
findfiles(f)
elif os.path.isfile(f):
if re.search(filename,f):
result.append(f)
print('[%d,\'%s\']'%(len(result),f))
#非递归版本
def findf():
dire = os.listdir(path)
paths = []
for d in dire:
paths.append(os.path.join(path,d))
for p in paths:
if os.path.isdir(p):
dire = os.listdir(p)
for d in dire:
paths.append(os.path.join(p,d))
elif os.path.isfile(p):
if re.search(filename,p):
result.append(p)
for i in range(len(result)):
print('[%d,\'%s\']'%(i+1,result[i]))
不过这些都不是重点,day01的重点是 百度AI技术体验传送门,体验这个,对AI的兴趣大增,也了解到了当前商业化应用AI的典型样例(PS:动漫头像制作好评~~~)
day02
学习的爬虫,以前简单了解过,但是没用过bs4。这次使用bs4简直就是如有神助,比正则舒服多了。
import json
import re
import requests
import datetime
from bs4 import BeautifulSoup
import os
#获取当天的日期,并进行格式化,用于后面文件命名,格式:20200420
today = datetime.date.today().strftime('%Y%m%d')
def crawl_wiki_data():
"""
爬取百度百科中《青春有你2》中参赛选手信息,返回html
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
url='https://baike.baidu.com/item/青春有你第二季'
try:
response = requests.get(url,headers=headers)
print(response.status_code)
#将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
soup = BeautifulSoup(response.text,'lxml')
#返回的是class为table-view log-set-param的<table>所有标签
tables = soup.find_all('table',{'class':'table-view log-set-param'})
crawl_table_title = "参赛学员"
for table in tables:
#对当前节点前面的标签和字符串进行查找
table_titles = table.find_previous('div').find_all('h3')
for title in table_titles:
if(crawl_table_title in title):
return table
except Exception as e:
print(e)
def parse_wiki_data(table_html):
'''
从百度百科返回的html中解析得到选手信息,以当前日期作为文件名,存JSON文件,保存到work目录下
'''
bs = BeautifulSoup(str(table_html),'lxml')
all_trs = bs.find_all('tr')
error_list = ['\'','\"']
stars = []
for tr in all_trs[1:]:
all_tds = tr.find_all('td')
star = {}
#姓名
star["name"]=all_tds[0].text
#个人百度百科链接
star["link"]= 'https://baike.baidu.com' + all_tds[0].find('a').get('href')
#籍贯
star["zone"]=all_tds[1].text
#星座
star["constellation"]=all_tds[2].text
#身高
star["height"]=all_tds[3].text
#体重
star["weight"]= all_tds[4].text
#花语,去除掉花语中的单引号或双引号
flower_word = all_tds[5].text
for c in flower_word:
if c in error_list:
flower_word=flower_word.replace(c,'')
star["flower_word"]=flower_word
#公司
if not all_tds[6].find('a') is None:
star["company"]= all_tds[6].find('a').text
else:
star["company"]= all_tds[6].text
stars.append(star)
json_data = json.loads(str(stars).replace("\'","\""))
with open('work/' + today + '.json', 'w', encoding='UTF-8') as f:
json.dump(json_data, f, ensure_ascii=False)
def crawl_pic_urls():
'''
爬取每个选手的百度百科图片,并保存
'''
with open('work/'+ today + '.json', 'r', encoding='UTF-8') as file:
json_array = json.loads(file.read())
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
for star in json_array:
name = star['name']
link = star['link']
#!!!请在以下完成对每个选手图片的爬取,将所有图片url存储在一个列表pic_urls中!!!
pic_urls = []
link2pic = getpichtml(link)
pic_urls = getpicurl(link2pic)
#!!!根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中!!!
down_pic(name,pic_urls)
def getpichtml(url):
'''
获取选手的百度相册地址
'''
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
try:
response = requests.get(url,headers=headers)
#将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
soup = BeautifulSoup(response.text,'lxml')
#找到相册的连接地址并返回
link2 = soup.find('a',{'nslog-type':'10002401'}).get("href")
except Exception as e:
print(e)
return 'https://baike.baidu.com'+link2
def getpicurl(url):
'''
获取选手相册的每一张图片的地址
'''
result = []
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
try:
response = requests.get(url,headers=headers)
#将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
soup = BeautifulSoup(response.text,'lxml')
#找到相册的连接地址并返回
link = soup.find_all('a',{'class':'pic-item'})
for item in link:
#print(item.find("img")['src'])
result.append(item.find("img")['src'])
except Exception as e:
print(e)
return result
def down_pic(name,pic_urls):
'''
根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中,
'''
path = 'work/'+'pics/'+name+'/'
if not os.path.exists(path):
os.makedirs(path)
for i, pic_url in enumerate(pic_urls):
try:
pic = requests.get(pic_url, timeout=15)
string = str(i + 1) + '.jpg'
with open(path+string, 'wb') as f:
f.write(pic.content)
print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))
except Exception as e:
print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))
print(e)
continue
day03
学习的是数据可视化,使用plt来绘制图片,这个还可以,唯一遗憾的地方是没有使用pychart,图片有点点丑。。。
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.figure(figsize=(10,8))
plt.pie(x=x,labels=labels,explode=(0,0.1,0.1,0.2),autopct='%1.1f%%',shadow=True,startangle=0,textprops={'fontsize':15,'color':'black'})
plt.axis('equal')
plt.legend()
plt.title('''《青春有你2》参赛选手体重分布''',fontsize = 24)
使用中文是个大坑这个下载地址好像出问题了,大家可以自己去其它地方下一个,然后上传到aistudio即可
#aistudio平台代码如下
# 下载中文字体
!wget https://mydueros.cdn.bcebos.com/font/simhei.ttf
# 将字体文件复制到matplotlib字体路径
!cp simhei.ttf /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf/
# 一般只需要将字体文件复制到系统字体目录下即可,但是在aistudio上该路径没有写权限,所以此方法不能用
# !cp simhei.ttf /usr/share/fonts/
# 创建系统字体文件路径
!mkdir .fonts
# 复制文件到该路径
!cp simhei.ttf .fonts/
!rm -rf .cache/matplotlib
day04
学习图片分类,要求分五类,但是图片不好找呀,尤其是anqi的,数据集就搞了好久。
这时百度百科爬的图片
import re
import requests
from bs4 import BeautifulSoup
import os
def getpichtml(url):
link = []
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
try:
response = requests.get(url,headers=headers)
#将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
soup = BeautifulSoup(response.text,'html.parser')
#找到相册的连接地址并返回
link.append('https://baike.baidu.com'+soup.find('a',{'nslog-type':'10002401'}).get("href"))
for link2 in soup.find_all('a',{'class':'lemma-album layout-right nslog:10000206'}):
link.append('https://baike.baidu.com'+link2.get("href"))
except Exception as e:
print(e)
return link
def getpicurl(url):
'''
获取选手相册的每一张图片的地址
'''
result = []
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
try:
response = requests.get(url,headers=headers)
#将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
soup = BeautifulSoup(response.text,'html.parser')
link = soup.find_all('a',{'class':'pic-item'})
for item in link:
#print(item.find("img")['src'])
result.append(item.find("img")['src'])
except Exception as e:
print(e)
return result
def down_pic(name,pic_urls):
'''
根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中,
'''
path = 'dataset/'+name+'/'
if not os.path.exists(path):
os.makedirs(path)
for i, pic_url in enumerate(pic_urls):
try:
pic = requests.get(pic_url, timeout=15)
string = str(i + 1) + '.jpg'
with open(path+string, 'wb') as f:
f.write(pic.content)
print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))
except Exception as e:
print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))
print(e)
continue
urls = [
'https://baike.baidu.com/item/%E8%99%9E%E4%B9%A6%E6%AC%A3/2977841', #yushuxin
'https://baike.baidu.com/item/%E8%AE%B8%E4%BD%B3%E7%90%AA/4970805', #xujiaqi
'https://baike.baidu.com/item/%E8%B5%B5%E5%B0%8F%E6%A3%A0/24274480', #zhaoxiaotang
'https://baike.baidu.com/item/%E5%AE%89%E5%B4%8E/22831154', #anqi
'https://baike.baidu.com/item/%E7%8E%8B%E6%89%BF%E6%B8%B2/24275812' #wangchengxuan
]
file_name=['yushuxin','xujiaqi','zhaoxiaotang','anqi','wangchengxuan']
iii=0
for url in urls:
links = []
links = getpichtml(url)
pic_url = []
for lin in links:
pic_url.extend(getpicurl(lin))
down_pic(file_name[iii],pic_url)
iii = iii+1
图片一定一定要自己清洗一下,不然后面报错报个没完
# from PIL import Image
# urls = os.listdir('./dataset/anqi/')
# for url in urls:
# tmp = './dataset/anqi/'+url
# try:
# Image.open(tmp).load()
# except OSError:
# os.remove(tmp)
# print(tmp)
配置paddlehub来训练,这个东东简化了好多好多好多步骤,一个训练可能10来行就完事了,用了这个完全不想用pytorch了
import paddlehub as hub
module = hub.Module(name="resnet_v2_50_imagenet")
from paddlehub.dataset.base_cv_dataset import BaseCVDataset
class DemoDataset(BaseCVDataset):
def __init__(self):
# 数据集存放位置
self.dataset_dir = "/home/aistudio/dataset" #这个是文件夹地址,里面有train_list.txt这些
super(DemoDataset, self).__init__(
base_path=self.dataset_dir,
train_list_file="train_list.txt",
validate_list_file="validate_list.txt",
test_list_file="test_list.txt",
label_list_file="label_list.txt",
)
dataset = DemoDataset()
#生成数据集这个是
import os
with open('./dataset/train_list.txt','w') as f:
for root, dirs, files in os.walk("./dataset/yushuxin", topdown=False):
for ind in files:
s = 'yushuxin/'+ind+' 0\n'
f.write(s)
for root, dirs, files in os.walk("./dataset/xujiaqi", topdown=False):
for ind in files:
s = 'xujiaqi/'+ind+' 1\n'
f.write(s)
for root, dirs, files in os.walk("./dataset/zhaoxiaotang", topdown=False):
for ind in files:
s = 'zhaoxiaotang/'+ind+' 2\n'
f.write(s)
for root, dirs, files in os.walk("./dataset/anqi", topdown=False):
for ind in files:
s = 'anqi/'+ind+' 3\n'
f.write(s)
for root, dirs, files in os.walk("./dataset/wangchengxuan", topdown=False):
for ind in files:
s = 'wangchengxuan/'+ind+' 4\n'
f.write(s)
data_reader = hub.reader.ImageClassificationReader(
image_width=module.get_expected_image_width(),
image_height=module.get_expected_image_height(),
images_mean=module.get_pretrained_images_mean(),
images_std=module.get_pretrained_images_std(),
dataset=dataset)
配置策略
在进行Finetune前,我们可以设置一些运行时的配置,例如如下代码中的配置,表示:use_cuda:设置为False表示使用CPU进行训练。如果您本机支持GPU,且安装的是GPU版本的PaddlePaddle,我们建议您将这个选项设置为True;
epoch:迭代轮数;
batch_size:每次训练的时候,给模型输入的每批数据大小为32,模型训练时能够并行处理批数据,因此batch_size越大,训练的效率越高,但是同时带来了内存的负荷,过大的batch_size可能导致内存不足而无法训练,因此选择一个合适的batch_size是很重要的一步;
log_interval:每隔10 step打印一次训练日志;
eval_interval:每隔50 step在验证集上进行一次性能评估;
checkpoint_dir:将训练的参数和数据保存到cv_finetune_turtorial_demo目录中;
strategy:使用DefaultFinetuneStrategy策略进行finetune;
更多运行配置,请查看RunConfig
同时PaddleHub提供了许多优化策略,如AdamWeightDecayStrategy、ULMFiTStrategy、DefaultFinetuneStrategy等,详细信息参见策略
config = hub.RunConfig(
use_cuda=True, #是否使用GPU训练,默认为False;
num_epoch=10, #Fine-tune的轮数;
checkpoint_dir="cv_finetune_turtorial_demo",#模型checkpoint保存路径, 若用户没有指定,程序会自动生成;
batch_size=8, #训练的批大小,如果使用GPU,请根据实际情况调整batch_size;
eval_interval=20, #模型评估的间隔,默认每100个step评估一次验证集;
strategy=hub.finetune.strategy.L2SPFinetuneStrategy(learning_rate=1e-4,optimizer_name="adam",regularization_coeff=1e-3)) #Fine-tune优化策略;
组建Finetune Task
有了合适的预训练模型和准备要迁移的数据集后,我们开始组建一个Task。由于该数据设置是一个二分类的任务,而我们下载的分类module是在ImageNet数据集上训练的千分类模型,所以我们需要对模型进行简单的微调,把模型改造为一个二分类模型:
获取module的上下文环境,包括输入和输出的变量,以及Paddle Program; 从输出变量中找到特征图提取层feature_map;
在feature_map后面接入一个全连接层,生成Task;
input_dict, output_dict, program = module.context(trainable=True)
img = input_dict["image"]
feature_map = output_dict["feature_map"]
feed_list = [img.name]
task = hub.ImageClassifierTask(
data_reader=data_reader,
feed_list=feed_list,
feature=feature_map,
num_classes=dataset.num_labels,
config=config)
开始Finetune
我们选择finetune_and_eval接口来进行模型训练,这个接口在finetune的过程中,会周期性的进行模型效果的评估,以便我们了解整个训练过程的性能变化。
run_states = task.finetune_and_eval()
训练完以后的预测结果
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
with open("./dataset/test_list.txt","r") as f:
filepath = f.readlines()
#data = [filepath[0].split(" ")[0],filepath[1].split(" ")[0],filepath[2].split(" ")[0],filepath[3].split(" ")[0],filepath[4].split(" ")[0]]
data = ['dataset/'+filepath[0].split(" ")[0],'dataset/'+filepath[1].split(" ")[0],'dataset/'+filepath[2].split(" ")[0],'dataset/'+filepath[3].split(" ")[0],'dataset/'+filepath[4].split(" ")[0]]
label_map = dataset.label_dict()
index = 0
run_states = task.predict(data=data)
results = [run_state.run_results for run_state in run_states]
for batch_result in results:
print(batch_result)
batch_result = np.argmax(batch_result, axis=2)[0]
print(batch_result)
for result in batch_result:
index += 1
result = label_map[result]
print("input %i is %s, and the predict result is %s" %
(index, data[index - 1], result))
day05
大作业,听着就叫人头大,爱奇艺的评论爬取就爬了一天,还是晚上听了小哥哥的讲解才学会如何正确的爬取那些东东。
这种样子的bs4已经没用用武之地了,分析network,找他的评论
这时request的URL,多抓几个你会发现,只有last_id不同,而且第一个的last_id后面不用写,而这个last_id就是上面json文件中最后一个评论用户的id,url里面的page_size 也可改变,表示最大加载多少评论,最大可以改到40。
https://sns-comment.iqiyi.com/v3/comment/get_comments.action?agent_type=118&agent_version=9.11.5&authcookie=null&business_type=17&content_id=15305002700&hot_size=10&last_id=&page=&page_size=10&types=hot,time
https://sns-comment.iqiyi.com/v3/comment/get_comments.action?agent_type=118&agent_version=9.11.5&authcookie=null&business_type=17&content_id=15305002700&hot_size=0&last_id=241161657921&page=&page_size=20&types=time
https://sns-comment.iqiyi.com/v3/comment/get_comments.action?agent_type=118&agent_version=9.11.5&authcookie=null&business_type=17&content_id=15305002700&hot_size=0&last_id=241064309921&page=&page_size=20&types=time
了解到这里,就可以欢快的开始爬取评论了:
from __future__ import print_function
import requests
import json
import re #正则匹配
import time #时间处理模块
import jieba #中文分词
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
from PIL import Image
from wordcloud import WordCloud #绘制词云模块
import paddlehub as hub
#请求爱奇艺评论接口,返回response信息
def getMovieinfo(url):
'''
请求爱奇艺评论接口,返回response信息
参数 url: 评论的url
:return: response信息
'''
session = requests.Session()
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36",
"Accept": "application/json",
"Referer": "https://www.iqiyi.com/v_19ryfkiv8w.html",
"Origin": "http://m.iqiyi.com",
"Host": "sns-comment.iqiyi.com",
"Connection": "keep-alive",
"Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6",
"Accept-Encoding": "gzip, deflate,br"
}
response = session.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
#解析json数据,获取评论
def saveMovieInfoToFile(lastId,arr):
'''
解析json数据,获取评论
参数 lastId:最后一条评论ID arr:存放文本的list
:return: 新的lastId
'''
url = "https://sns-comment.iqiyi.com/v3/comment/get_comments.action?agent_type=118&agent_version=9.11.5&authcookie=null&business_type=17&content_id=15068699100&hot_size=0&page=&page_size=20&types=time&last_id="
url += str(lastId)
responseText = getMovieinfo(url)
responseJson = json.loads(responseText)
comments = responseJson['data']['comments']
for val in comments:
if 'content' in val.keys():
print(val['content'])
arr.append(val['content'])
lastId = str(val['id'])
return lastId
#去除文本中特殊字符
def clear_special_char(content):
'''
正则处理特殊字符
参数 content:原文本
return: 清除后的文本
'''
s = re.sub(r'</?(.+?)>| |\t|\r',"",content)
s = re.sub(r'\n'," ",s)
s = re.sub(r'\*',"\\*",s)
s = re.sub('[^\u4e00-\u9fa5^a-z^A-Z^0-9]','',s)
s = re.sub('[\001\002\003\004\005\006\007\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a]','',s)
s = re.sub('[a-zA-Z]','',s)
s = re.sub('^\d+(\.\d+)?$','',s)
return s
add_words.txt就是一个人工添加的词语,比如 奥里给,冲鸭 这些jieba不懂的
def fenci(text):
'''
利用jieba进行分词
参数 text:需要分词的句子或文本
return:分词结果
'''
jieba.load_userdict('add_words.txt')
seg = jieba.lcut(text,cut_all=False)
return seg
停词表就是 可以,只是,因为 这类的没用实际意义的词语
def stopwordslist(file_path):
'''
创建停用词表
参数 file_path:停用词文本路径
return:停用词list
'''
stopwords = [line.strip() for line in open(file_path,encoding='UTF-8').readlines()]
return stopwords
def movestopwords(sentence,stopwords,counts):
'''
去除停用词,统计词频
参数 file_path:停用词文本路径 stopwords:停用词list counts: 词频统计结果
return:None
'''
out = []
for word in sentence:
if word not in stopwords:
if len(word) != 1:
counts[word] = counts.get(word,0) + 1
return None
def drawcounts(counts,num):
'''
绘制词频统计表
参数 counts: 词频统计结果 num:绘制topN
return:none
'''
x_aixes = []
y_aixes = []
c_order = sorted(counts.items(),key=lambda x:x[1],reverse=True)
for c in c_order[:num]:
x_aixes.append(c[0])
y_aixes.append(c[1])
matplotlib.rcParams['font.sans-serif'] = ['simhei']
matplotlib.rcParams['axes.unicode_minus'] = False #解决图片负号 - 保存显示方块问题
plt.bar(x_aixes,y_aixes)
plt.title("词频统计")
plt.show()
return None
def drawcloud(word_f):
'''
根据词频绘制词云图
参数 word_f:统计出的词频结果
return:none
'''
#print(word_f)
#加载背景图片
cloud_mask = np.array(Image.open("./4.jpg"))
#忽略显示的词
st=set(['可是'])
#生成wordcloud对象
wc = WordCloud(background_color="white",
mask=cloud_mask,
max_words=300,
font_path="STFANGSO.TTF",
stopwords=st)
# 加载词频字典
wc.fit_words(word_f)
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()
wc.to_file("pic.png")
def text_detection(text_text,file_path):
'''
使用hub对评论进行内容分析
return:分析结果
'''
porn_detection_lstm = hub.Module(name='porn_detection_lstm')
f = open('aqy.txt','r',encoding='utf-8')
for line in f:
if len(line.strip() ) == 1:
continue
else:
text_text.append(line)
f.close()
input_dict = {"text":text_text}
results = porn_detection_lstm.detection(data=input_dict,use_gpu=True,batch_size=1)
for index,item in enumerate(results):
if item['porn_detection_key'] == 'porn':
print(item['text'],":",item['porn_probs'])
#评论是多分页的,得多次请求爱奇艺的评论接口才能获取多页评论,有些评论含有表情、特殊字符之类的
#num 是页数,一页10条评论,假如爬取1000条评论,设置num=100
if __name__ == "__main__":
num = 60
lastId = '0'
arr = []
with open('aqy.txt','a',encoding='utf-8') as f:
for i in range(num):
lastId = saveMovieInfoToFile(lastId,arr)
time.sleep(0.5)
for item in arr:
Item = clear_special_char(item)
if Item.strip() !='':
try:
f.write(Item+'\n')
except Exception as e:
print('含有特殊字符')
print('共获取评论: ',len(arr))
f = open('aqy.txt','r',encoding='utf-8')
counts = {}
for line in f:
words = fenci(line)
stopwords = stopwordslist('stopwords-cn.txt')
movestopwords(words,stopwords,counts)
drawcounts(counts,10)
drawcloud(counts)
f.close()
file_path = 'aqy.txt'
text_text = []
text_detection(text_text,file_path)
经过这一期打卡营,python基础有了很大的提高,以前不懂的一些东西,现在听力讲解有一种原来如此的感觉。