
正文
python的con函数 python中conv函数
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
python中的count函数问题?
统计一个列表中每一个元素python的con函数的个数在Python里有两种实现方式python的con函数,
第一种是新建一个dictpython的con函数,键是列表中python的con函数的元素python的con函数,值是统计的个数,然后遍历list。
items = ["cc","cc","ct","ct","ac"]
count = {}
for item in items:
count[item] = count.get(item, 0) + 1
print(count)
#{'ac': 1, 'ct': 2, 'cc': 2}
之中用到了一个小技巧,当dict中不还没有统计过一个元素时,直接索引count[item]会报错,而使用get方法count.get(item, 0)能够设置索引不存在的键时返回0。
第二种是使用Python内置的函数。统计元素的个数是一种非常常见的操作,Python的collection包里已经有一个Counter的类,大致实现了上面的功能。
from collections import Counter
items = ["cc","cc","ct","ct","ac"]
count = Counter(items)
print(count)
#Counter({'ct': 2, 'cc': 2, 'ac': 1})
相关问答
Q1: 如何用python获取websocket数据
这里python的con函数,介绍如何使用 Python 与前端 js 进行通信。
websocket 使用 HTTP 协议完成握手之后,不通过 HTTP 直接进行 websocket 通信。
于是,使用 websocket 大致两个步骤python的con函数:使用 HTTP 握手,通信。
js 处理 websocket 要使用 ws 模块python的con函数; python 处理则使用 socket 模块建立 TCP 连接即可,比一般python的con函数的 socket ,只多一个握手以及数据处理的步骤。
握手
过程
包格式
js 客户端先向服务器端 python 发送握手包,格式如下python的con函数:
?
1
2
3
4
5
6
7
8
GET
/chat HTTP/1.1
Host:
server.example.com
Upgrade:
websocket
Connection:
Upgrade
Sec-WebSocket-Key:
dGhlIHNhbXBsZSBub25jZQ==
Origin:
Sec-WebSocket-Protocol:
chat, superchat
Sec-WebSocket-Version:
13
服务器回应包格式:
?
1
2
3
4
5
HTTP/1.1
101 Switching Protocols
Upgrade:
websocket
Connection:
Upgrade
Sec-WebSocket-Accept:
s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol:
chat
其中, Sec-WebSocket-Key 是随机的,服务器用这些数据构造一个 SHA-1 信息摘要。
方法为: key+migic , SHA-1 加密, base-64 加密,如下:
Python 中的处理代码
?
1
2
MAGIC_STRING='258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
res_key=base64.b64encode(hashlib.sha1(sec_key
+MAGIC_STRING).digest())
握手完整代码
js 端
js 中有处理 websocket 的类,初始化后自动发送握手包,如下:
var socket = new WebSocket('ws://localhost:3368');
Python 端
Python 用 socket 接受得到握手字符串,处理后发送
?
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
HOST='localhost'
PORT=3368
MAGIC_STRING='258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
HANDSHAKE_STRING="HTTP/1.1
101 Switching Protocols\r\n"
\
"Upgrade:websocket\r\n"\
"Connection:
Upgrade\r\n"
\
"Sec-WebSocket-Accept:
{1}\r\n"
\
"WebSocket-Location:ws://{2}/chat\r\n"
\
"WebSocket-Protocol:chat\r\n\r\n"
defhandshake(con):
#con为用socket,accept()得到的socket
headers={}
shake=con.recv(1024)
ifnot
len(shake):
returnFalse
header,
data =shake.split('\r\n\r\n',1)
forline
inheader.split('\r\n')[1:]:
key,
val =line.split(':
',1)
headers[key]=val
if'Sec-WebSocket-Key'
not
in
headers:
print('This
socket is not websocket, client close.')
con.close()
returnFalse
sec_key=headers['Sec-WebSocket-Key']
res_key=base64.b64encode(hashlib.sha1(sec_key
+MAGIC_STRING).digest())
str_handshake=HANDSHAKE_STRING.replace('{1}',
res_key).replace('{2}',
HOST +':'
+
str(PORT))
printstr_handshake
con.send(str_handshake)
returnTrue
通信
不同版本的浏览器定义的数据帧格式不同, Python 发送和接收时都要处理得到符合格式的数据包,才能通信。
Python 接收
Python 接收到浏览器发来的数据,要解析后才能得到其中的有用数据。
浏览器包格式
固定字节:
( 1000 0001 或是 1000 0002 )这里没用,忽略
包长度字节:
第一位肯定是 1 ,忽略。剩下 7 个位可以得到一个整数 (0 ~ 127) ,其中
( 1-125 )表此字节为长度字节,大小即为长度;
(126)表接下来的两个字节才是长度;
(127)表接下来的八个字节才是长度;
用这种变长的方式表示数据长度,节省数据位。
mark 掩码:
mark 掩码为包长之后的 4 个字节,之后的兄弟数据要与 mark 掩码做运算才能得到真实的数据。
兄弟数据:
得到真实数据的方法:将兄弟数据的每一位 x ,和掩码的第 i%4 位做 xor 运算,其中 i 是 x 在兄弟数据中的索引。
完整代码
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
defrecv_data(self,
num):
try:
all_data=self.con.recv(num)
ifnot
len(all_data):
returnFalse
except:
returnFalse
else:
code_len=ord(all_data[1])
127
ifcode_len
==126:
masks=all_data[4:8]
data=all_data[8:]
elifcode_len
==127:
masks=all_data[10:14]
data=all_data[14:]
else:
masks=all_data[2:6]
data=all_data[6:]
raw_str=""
i=0
ford
indata:
raw_str+=chr(ord(d)
^ ord(masks[i%4]))
i+=1
returnraw_str
js 端的 ws 对象,通过 ws.send(str) 即可发送
ws.send(str)
Python 发送
Python 要包数据发送,也需要处理,发送包格式如下
固定字节:固定的 1000 0001( ‘ \x81 ′ )
包长:根据发送数据长度是否超过 125 , 0xFFFF(65535) 来生成 1 个或 3 个或 9 个字节,来代表数据长度。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
defsend_data(self,
data):
ifdata:
data=str(data)
else:
returnFalse
token="\x81"
length=len(data)
iflength
126:
token+=struct.pack("B",
length)
eliflength
=0xFFFF:
token+=struct.pack("!BH",126,
length)
else:
token+=struct.pack("!BQ",127,
length)
#struct为Python中处理二进制数的模块,二进制流为C,或网络流的形式。
data='%s%s'
%
(token, data)
self.con.send(data)
returnTrue
js 端通过回调函数 ws.onmessage() 接受数据
?
1
2
3
4
5
ws.onmessage
= function(result,nTime){
alert("从服务端收到的数据:");
alert("最近一次发送数据到现在接收一共使用时间:"+
nTime);
console.log(result);
}
最终代码
Python服务端
?
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#
_*_ coding:utf-8 _*_
__author__='Patrick'
importsocket
importthreading
importsys
importos
importMySQLdb
importbase64
importhashlib
importstruct
#
====== config ======
HOST='localhost'
PORT=3368
MAGIC_STRING='258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
HANDSHAKE_STRING="HTTP/1.1
101 Switching Protocols\r\n"
\
"Upgrade:websocket\r\n"\
"Connection:
Upgrade\r\n"
\
"Sec-WebSocket-Accept:
{1}\r\n"
\
"WebSocket-Location:ws://{2}/chat\r\n"
\
"WebSocket-Protocol:chat\r\n\r\n"
classTh(threading.Thread):
def__init__(self,
connection,):
threading.Thread.__init__(self)
self.con=connection
defrun(self):
whileTrue:
try:
pass
self.con.close()
defrecv_data(self,
num):
try:
all_data=self.con.recv(num)
ifnot
len(all_data):
returnFalse
except:
returnFalse
else:
code_len=ord(all_data[1])
127
ifcode_len
==126:
masks=all_data[4:8]
data=all_data[8:]
elifcode_len
==127:
masks=all_data[10:14]
data=all_data[14:]
else:
masks=all_data[2:6]
data=all_data[6:]
raw_str=""
i=0
ford
indata:
raw_str+=chr(ord(d)
^ ord(masks[i%4]))
i+=1
returnraw_str
#
send data
defsend_data(self,
data):
ifdata:
data=str(data)
else:
returnFalse
token="\x81"
length=len(data)
iflength
126:
token+=struct.pack("B",
length)
eliflength
=0xFFFF:
token+=struct.pack("!BH",126,
length)
else:
token+=struct.pack("!BQ",127,
length)
#struct为Python中处理二进制数的模块,二进制流为C,或网络流的形式。
data='%s%s'
%
(token, data)
self.con.send(data)
returnTrue
#
handshake
defhandshake(con):
headers={}
shake=con.recv(1024)
ifnot
len(shake):
returnFalse
header,
data =shake.split('\r\n\r\n',1)
forline
inheader.split('\r\n')[1:]:
key,
val =line.split(':
',1)
headers[key]=val
if'Sec-WebSocket-Key'
not
in
headers:
print('This
socket is not websocket, client close.')
con.close()
returnFalse
sec_key=headers['Sec-WebSocket-Key']
res_key=base64.b64encode(hashlib.sha1(sec_key
+MAGIC_STRING).digest())
str_handshake=HANDSHAKE_STRING.replace('{1}',
res_key).replace('{2}',
HOST +':'
+
str(PORT))
printstr_handshake
con.send(str_handshake)
returnTrue
defnew_service():
"""start
a service socket and listen
when
coms a connection, start a new thread to handle it"""
sock=socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
try:
sock.bind(('localhost',3368))
sock.listen(1000)
#链接队列大小
print"bind
3368,ready to use"
except:
print("Server
is already running,quit")
sys.exit()
whileTrue:
connection,
address =sock.accept()
#返回元组(socket,add),accept调用时会进入waite状态
print"Got
connection from ",
address
ifhandshake(connection):
print"handshake
success"
try:
t=Th(connection,
layout)
t.start()
print'new
thread for client ...'
except:
print'start
new thread error'
connection.close()
if__name__
=='__main__':
new_service()
js客户 端
?
1
2
3
4
5
6
7
8
script
varsocket
= newWebSocket('ws://localhost:3368');
ws.onmessage
= function(result,nTime){
alert("从服务端收到的数据:");
alert("最近一次发送数据到现在接收一共使用时间:"+
nTime);
console.log(result);
}
/script
Q2: 基于Python的条件函数(Con)批量处理
在输入条件栅格数据值小于0 的原始值将在输出中保存为 0,输出中保留在输入条件栅格数据值大于 0 的原始值。
Q3: Python数据库连接以及游标关闭问题
MySQLdb.connect是python 连接MySQL数据库的方法,在Python中 import MySQLdb即可使用,至于connect中的参数很简单:
host:MySQL服务器名
user:数据库使用者
password:用户登录密码
db:操作的数据库名
charset:使用的字符集(一般是gb2312)
cursor = db.cursor() 其实就是用来获得python执行Mysql命令的方法,也就是
我们所说的操作游标
下面cursor.execute则是真正执行MySQL语句,即查询TABLE_PARAMS表的数据。
至于fetchall()则是接收全部的返回结果行 row就是在python中定义的一个变量,用来接收返回结果行的每行数据。同样后面的r也是一个变量,用来接收row中的每个字符,如果写成C的形式就更好理解了
for(string row = ''; row= cursor.fetchall(): row++)
for(char r = ''; r= row; r++)
printf("%c", r);
Q4: python中, break和continue都是函数吗?
break,continue是保留字,不是函数。保留字主要是表示语法,运算的。
Q5: python count()函数的功能和用法
python count()函数的功能和用法如下:
统计字符串
在python中可以使用“count()”函数统计字符串里某个字符出现的次数,该函数用于统计次数,其语法是“count(sub, start...
Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
count()函数
描述:统计字符串里某个字符出现的次数。可以选择字符串索引的起始位置和结束位置。
语法:str.count("char", start,end) 或 str.count("char") - int 返回整数
str —— 为要统计的字符(可以是单字符,也可以是多字符)。
star —— 为索引字符串的起始位置,默认参数为0。
end —— 为索引字符串的结束位置,默认参数为字符串长度即len(str)
python的con函数的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于python中conv函数、python的con函数的信息别忘了在本站进行查找喔。







