Skip to content

Commit 973ea74

Browse files
author
zhaww
committed
把微信itchat 模块,娱乐模块导入
1 parent 1f24bb4 commit 973ea74

20 files changed

+395
-0
lines changed

venv/Include/amusement/01.jpg

465 KB
Loading

venv/Include/amusement/02.jpg

151 KB
Loading

venv/Include/amusement/03.jpg

21.5 KB
Loading

venv/Include/amusement/04.jpg

24 KB
Loading

venv/Include/amusement/06.gif

93.4 KB
Loading

venv/Include/amusement/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# -*- coding:utf-8 -*-
2+
# Author: zww
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# -*- coding:utf-8 -*-
2+
# Author: zww
3+
4+
from Include.commons.common import Common
5+
from bs4 import BeautifulSoup
6+
7+
def getData(html_text):
8+
final = []
9+
bs = BeautifulSoup(html_text, "html.parser") # 创建BeautifulSoup对象
10+
body = bs.body #获取body
11+
data = body.find('div',{'id': '7d'})
12+
ul = data.find('ul')
13+
li = ul.find_all('li')
14+
15+
for day in li:
16+
temp = []
17+
date = day.find('h1').string
18+
temp.append(date) #添加日期
19+
inf = day.find_all('p')
20+
weather = inf[0].string #天气
21+
temp.append(weather)
22+
temperature_highest = inf[1].find('span').string #最高温度
23+
temperature_low = inf[1].find('i').string # 最低温度
24+
temp.append(temperature_highest)
25+
temp.append(temperature_low)
26+
final.append(temp)
27+
print('getDate success')
28+
return final
29+
30+
if __name__ == '__main__':
31+
common = Common()
32+
# url ='http://www.weather.com.cn/weather/101210101.shtml'
33+
url = 'https://rate.tmall.com/list_detail_rate.htm?itemId=566445932680&sellerId=2451699564&order=3&currentPage=1&append=0callback=jsonp336'
34+
# itemId 产品id ; sellerId 店铺id 字段必须有值,但随意值就行
35+
html = common.getUrlContent(url) # 获取网页信息
36+
result = getData(html) # 解析网页信息,拿到需要的数据
37+
common.writeData(result, 'D:/py_work/venv/Include/amusement/weather.csv') #数据写入到 csv文档中
38+
# createTable() #表创建一次就好了,注意
39+
sql = 'insert into WEATHER(w_id, w_date, w_detail, w_temperature_low, w_temperature_high) value(null, %s,%s,%s,%s)'
40+
common.patchInsertData(sql, result) #批量写入数据
41+
print('my frist python file')

venv/Include/amusement/paint.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# -*- coding:utf-8 -*-
2+
# Author: zww
3+
4+
from PIL import Image
5+
#要索引的字符列表
6+
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
7+
length = len(ascii_char)
8+
img = Image.open('06-0.png') #读取图像文件
9+
(width,height) = img.size
10+
img = img.resize((int(width*1),int(height*1))) #对图像进行一定缩小
11+
print(img.size)
12+
def convert(img):
13+
img = img.convert("L") # 转为灰度图像
14+
txt = ""
15+
for i in range(img.size[1]):
16+
for j in range(img.size[0]):
17+
gray = img.getpixel((j, i)) # 获取每个坐标像素点的灰度
18+
unit = 256.0 / length
19+
txt += ascii_char[int(gray / unit)] #获取对应坐标的字符值
20+
txt += '\n'
21+
return txt
22+
23+
def convert1(img):
24+
txt = ""
25+
for i in range(img.size[1]):
26+
for j in range(img.size[0]):
27+
r,g,b = img.getpixel((j, i)) #获取每个坐标像素点的rgb值
28+
gray = int(r * 0.299 + g * 0.587 + b * 0.114) #通过灰度转换公式获取灰度
29+
unit = (256.0+1)/length
30+
txt += ascii_char[int(gray / unit)] # 获取对应坐标的字符值
31+
txt += '\n'
32+
return txt
33+
34+
txt = convert(img)
35+
f = open("04_convert.txt","w")
36+
f.write(txt) #存储到文件中
37+
f.close()

venv/Include/amusement/paintGif.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# -*- coding:utf-8 -*-
2+
# Author: zww
3+
import os
4+
from PIL import Image
5+
import imageio
6+
7+
def analyseImage(path):
8+
9+
im = Image.open(path)
10+
results = {
11+
'size': im.size,
12+
'mode': 'full',
13+
}
14+
try:
15+
while True:
16+
if im.tile:
17+
tile = im.tile[0]
18+
update_region = tile[1]
19+
update_region_dimensions = update_region[2:]
20+
if update_region_dimensions != im.size:
21+
results['mode'] = 'partial'
22+
break
23+
im.seek(im.tell() + 1)
24+
except EOFError:
25+
pass
26+
return results
27+
28+
29+
def processImage(path):
30+
mode = analyseImage(path)['mode']
31+
im = Image.open(path)
32+
i = 0
33+
p = im.getpalette()
34+
last_frame = im.convert('RGBA')
35+
36+
try:
37+
while True:
38+
print("saving %s (%s) frame %d, %s %s" % (path, mode, i, im.size, im.tile))
39+
40+
if not im.getpalette():
41+
im.putpalette(p)
42+
43+
new_frame = Image.new('RGBA', im.size)
44+
if mode == 'partial':
45+
new_frame.paste(last_frame)
46+
47+
new_frame.paste(im, (0, 0), im.convert('RGBA'))
48+
new_frame.save('%s-%d.png' % (''.join(os.path.basename(path).split('.')[:-1]), i), 'PNG')
49+
i += 1
50+
last_frame = new_frame
51+
im.seek(im.tell() + 1)
52+
except EOFError:
53+
pass
54+
55+
def create_gif():
56+
image_list = ['06-0.png', '06-2.png', '06-4.png',
57+
'06-6.png', '06-8.png', '06-10.png']
58+
gif_name = 'created_gif.gif'
59+
frames = []
60+
for image_name in image_list:
61+
frames.append(imageio.imread(image_name))
62+
# Save them as frames into a gif
63+
imageio.mimsave(gif_name, frames, 'GIF', duration=0.1)
64+
return
65+
66+
if __name__ == "__main__":
67+
processImage('D:/py_work/venv/Include/amusement/06.gif')
68+
# create_gif()

venv/Include/amusement/test_gif.gif

1.99 MB
Loading
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# -*- coding:utf-8 -*-
2+
# Author: zww
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# -*- coding:utf-8 -*-
2+
# Author: zww
3+
4+
from Include.commons.common import Common
5+
from bs4 import BeautifulSoup
6+
7+
def getData(html_text):
8+
final = []
9+
bs = BeautifulSoup(html_text, "html.parser") # 创建BeautifulSoup对象
10+
body = bs.body #获取body
11+
data = body.find('div',{'id': '7d'})
12+
ul = data.find('ul')
13+
li = ul.find_all('li')
14+
15+
for day in li:
16+
temp = []
17+
date = day.find('h1').string
18+
temp.append(date) #添加日期
19+
inf = day.find_all('p')
20+
weather = inf[0].string #天气
21+
temp.append(weather)
22+
temperature_highest = inf[1].find('span').string #最高温度
23+
temperature_low = inf[1].find('i').string # 最低温度
24+
temp.append(temperature_highest)
25+
temp.append(temperature_low)
26+
final.append(temp)
27+
print('getDate success')
28+
return final
29+
30+
def getRateDetail(common,itemId,currentPage):
31+
url = 'https://rate.tmall.com/list_detail_rate.htm?itemId=' + str(
32+
itemId) + '&sellerId=2451699564&order=3&currentPage=' + str(currentPage) + '&append=0callback=jsonp336'
33+
# itemId 产品id ; sellerId 店铺id 字段必须有值,但随意值就行
34+
html = common.getUrlContent(url) # 获取网页信息
35+
36+
html = html.replace('jsonp1278(','')
37+
html = html.replace(')','')
38+
html = html.replace('false','"false"')
39+
html = html.replace('true','"true"')
40+
# 将JSON格式的评论数据转换为字典对象
41+
tmalljson = json.loads(c)
42+
return tmalljson
43+
44+
if __name__ == '__main__':
45+
common = Common()
46+
url = 'https://rate.tmall.com/list_detail_rate.htm?itemId=' + str(itemId) +'&sellerId=2451699564&order=3&currentPage=' + str(currentPage) + '&append=0callback=jsonp336'
47+
# itemId 产品id ; sellerId 店铺id 字段必须有值,但随意值就行
48+
html = common.getUrlContent(url) # 获取网页信息
49+
result = getData(html) # 解析网页信息,拿到需要的数据
50+
common.writeData(result, 'D:/py_work/venv/Include/amusement/weather.csv') #数据写入到 csv文档中
51+
# createTable() #表创建一次就好了,注意
52+
sql = 'insert into WEATHER(w_id, w_date, w_detail, w_temperature_low, w_temperature_high) value(null, %s,%s,%s,%s)'
53+
common.patchInsertData(sql, result) #批量写入数据
54+
print('my frist python file')

venv/Include/amusement/weather.csv

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
29�գ����죩,����,34,26��
2+
30�գ����죩,����ת����,33,26��
3+
31�գ����죩,����,32,26��
4+
1�գ�������,����,32,25��
5+
2�գ����գ�,����ת����,31,26��
6+
3�գ���һ��,����,34,26��
7+
4�գ��ܶ���,����,34,26��
8+
29�գ����죩,����,34,26��
9+
30�գ����죩,����ת����,33,26��
10+
31�գ����죩,����,32,26��
11+
1�գ�������,����,32,25��
12+
2�գ����գ�,����ת����,31,26��
13+
3�գ���һ��,����,34,26��
14+
4�գ��ܶ���,����,34,26��

venv/Include/wechat/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# -*- coding:utf-8 -*-
2+
# Author: zww
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# -*- coding:utf-8 -*-
2+
# Author: zww
3+
4+
import itchat
5+
import re
6+
# jieba分词
7+
import jieba
8+
# wordcloud词云
9+
import matplotlib.pyplot as plt
10+
from wordcloud import WordCloud, ImageColorGenerator
11+
import os
12+
import numpy as np
13+
import PIL.Image as Image
14+
15+
class WeChat():
16+
17+
KEY = '71f9d9d2dd364ad8b28bd56527470176'
18+
19+
def login(self):
20+
itchat.auto_login(hotReload=True) # 登录,会下载二维码给手机扫描登录,hotReload设置为True表示以后自动登录
21+
itchat.run() # 让itchat一直运行
22+
23+
# 回复信息
24+
@itchat.msg_register(itchat.content.TEXT)
25+
def tuling_robot(self, msg):
26+
# 为了保证在图灵Key出现问题的时候仍旧可以回复,这里设置一个默认回复
27+
defaultReply = '不想说话了!'
28+
# 如果图灵Key出现问题,那么reply将会是None
29+
reply = self.getget_response(msg['Text'])
30+
# a or b的意思是,如果a有内容,那么返回a,否则返回b
31+
# 有内容一般就是指非空或者非None,你可以用`if a: print('True')`来测试
32+
return reply or defaultReply
33+
34+
def get_response(self, msg):
35+
# 构造了要发送给服务器的数据
36+
apiUrl = 'http://www.tuling123.com/openapi/api'
37+
data = {
38+
'key': KEY,
39+
'info': msg,
40+
'userid': 'wechat-robot',
41+
}
42+
try:
43+
r = requests.post(apiUrl, data=data).json()
44+
return r.get('text')
45+
# 为了防止服务器没有正常响应导致程序异常退出,这里用try-except捕获了异常
46+
# 如果服务器没能正常交互(返回非json或无法连接),那么就会进入下面的return
47+
except:
48+
# 将会返回一个None
49+
return
50+
51+
def getFriend(self, name):
52+
friends = itchat.search_friends(name = name) # 获取微信好友列表,如果设置update=True将从服务器刷新列表
53+
userName = friends[0]['UserName']
54+
return userName
55+
56+
def getFriends(self):
57+
friends = itchat.get_friends(update=True)[0:]
58+
return friends
59+
60+
def ratio(self, friends):
61+
# 初始化计数器,有男有女,当然,有些人是不填的
62+
male = female = other = 0
63+
64+
# 遍历这个列表,列表里第一位是自己,所以从"自己"之后开始计算
65+
# 1表示男性,2女性
66+
for i in friends[1:]:
67+
sex = i["Sex"]
68+
if sex == 1:
69+
male += 1
70+
elif sex == 2:
71+
female += 1
72+
else:
73+
other += 1
74+
75+
# 总数算上,好计算比例啊~
76+
total = len(friends[1:])
77+
# 好了,打印结果
78+
print(u"男性好友:%.2f%%" % (float(male) / total * 100))
79+
print(u"女性好友:%.2f%%" % (float(female) / total * 100))
80+
print(u"其他:%.2f%%" % (float(other) / total * 100))
81+
82+
def signature(self, friends):
83+
tList = []
84+
for i in friends:
85+
signature = i["Signature"].replace(" ", "").replace("span", "").replace("class", "").replace("emoji", "")
86+
rep = re.compile("1f\d.+")
87+
signature = rep.sub("", signature)
88+
tList.append(signature)
89+
text = "".join(tList)
90+
wordlist_jieba = jieba.cut(text, cut_all=True)
91+
wl_space_split = " ".join(wordlist_jieba)
92+
93+
d = os.path.dirname(__file__)
94+
alice_coloring = np.array(Image.open(os.path.join(d, "wechat1.png")))
95+
my_wordcloud = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,
96+
max_font_size=50, random_state=42,width=1000,height=860,
97+
font_path='C:/Windows/Fonts/STFANGSO.ttf').generate(wl_space_split)
98+
99+
image_colors = ImageColorGenerator(alice_coloring)
100+
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
101+
plt.imshow(my_wordcloud)
102+
plt.axis("off")
103+
plt.show()
104+
my_wordcloud.to_file(os.path.join(d, "wechat_cloud.png"))
105+
106+
# 这里要选择字体存放路径,这里是Mac的,win的字体在windows/Fonts中
107+
# my_wordcloud = WordCloud(background_color="white", max_words=2000,
108+
# max_font_size=40, random_state=42,
109+
# font_path='C:/Windows/Fonts/STFANGSO.ttf').generate(wl_space_split)
110+
# plt.imshow(my_wordcloud)
111+
# plt.axis("off")
112+
# plt.show()
113+
114+
def sendMessage(self, message, name):
115+
itchat.send(message, toUserName=name)
116+
117+
if __name__ == "__main__":
118+
wechat = WeChat()
119+
wechat.login()
120+
# item = wechat.getFriend('阿勇')
121+
# wechat.sendMessage("我是zww的python微信助手", item)
122+
# friends = wechat.getFriends()
123+
# wechat.signature(friends)
124+

0 commit comments

Comments
 (0)