Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jax_notebook #879

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Jax_code/Day1/day1_code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import this
43 changes: 43 additions & 0 deletions Jax_code/Day10/Code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import tkinter
import tkinter.messagebox


def main():
flag = True

# 修改标签上的文字
def change_label_text():
nonlocal flag
flag = not flag
color, msg = ('red', 'Hello, world!')\
if flag else ('blue', 'Goodbye, world!')
label.config(text=msg, fg=color)

# 确认退出
def confirm_to_quit():
if tkinter.messagebox.askokcancel('温馨提示', '确定要退出吗?'):
top.quit()

# 创建顶层窗口
top = tkinter.Tk()
# 设置窗口大小
top.geometry('240x160')
# 设置窗口标题
top.title('小游戏')
# 创建标签对象并添加到顶层窗口
label = tkinter.Label(top, text='Hello, world!', font='Arial -32', fg='red')
label.pack(expand=1)
# 创建一个装按钮的容器
panel = tkinter.Frame(top)
# 创建按钮对象 指定添加到哪个容器中 通过command参数绑定事件回调函数
button1 = tkinter.Button(panel, text='修改', command=change_label_text)
button1.pack(side='left')
button2 = tkinter.Button(panel, text='退出', command=confirm_to_quit)
button2.pack(side='right')
panel.pack(side='bottom')
# 开启主事件循环
tkinter.mainloop()


if __name__ == '__main__':
main()
Empty file added Jax_code/Day10/Note.md
Empty file.
16 changes: 16 additions & 0 deletions Jax_code/Day11/Code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from math import sqrt

def is_prime(n):
assert n > 0, f'Prime number ain\'t negative'
for factor in range(2, int(sqrt(n) + 1)):
if n % factor == 0:
return False
return True if n != 1 else False

def main():
number = int(input("Input a number:\n"))
print(is_prime(number))


if __name__ == '__main__':
main()
49 changes: 49 additions & 0 deletions Jax_code/Day11/Note.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
### 读写文本文件

在使用`open`函数时指定好文件名并将文件模式设置为`'w'`即可。注意如果需要对文件内容进行追加式写入,应该将模式设置为`'a'`


| JSON | Python |
| ------------------- | ------------ |
| object | dict |
| array | list |
| string | str |
| number (int / real) | int / float |
| true / false | True / False |
| null | None |

| Python | JSON |
| -------------------------------------- | ------------ |
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True / False | true / false |
| None | null |

json模块主要有四个比较重要的函数,分别是:

- `dump` - 将Python对象按照JSON格式序列化到文件中
- `dumps` - 将Python对象处理成JSON格式的字符串
- `load` - 将文件中的JSON数据反序列化成对象
- `loads` - 将字符串的内容反序列化成Python对象

这里出现了两个概念,一个叫序列化,一个叫反序列化。自由的百科全书[维基百科](https://zh.wikipedia.org/)上对这两个概念是这样解释的:“序列化(serialization)在计算机科学的数据处理中,是指将数据结构或对象状态转换为可以存储或传输的形式,这样在需要的时候能够恢复到原先的状态,而且通过序列化的数据重新获取字节时,可以利用这些字节来产生原始对象的副本(拷贝)。与这个过程相反的动作,即从一系列字节中提取数据结构的操作,就是反序列化(deserialization)”。

目前绝大多数网络数据服务(或称之为网络API)都是基于[HTTP协议](https://zh.wikipedia.org/wiki/%E8%B6%85%E6%96%87%E6%9C%AC%E4%BC%A0%E8%BE%93%E5%8D%8F%E8%AE%AE)提供JSON格式的数据,关于HTTP协议的相关知识,可以看看阮一峰老师的[《HTTP协议入门》](http://www.ruanyifeng.com/blog/2016/08/http.html),如果想了解国内的网络数据服务,可以看看[聚合数据](https://www.juhe.cn/)和[阿凡达数据](http://www.avatardata.cn/)等网站,国外的可以看看[{API}Search](http://apis.io/)网站。下面的例子演示了如何使用[requests](http://docs.python-requests.org/zh_CN/latest/)模块(封装得足够好的第三方网络访问模块)访问网络API获取国内新闻,如何通过json模块解析JSON数据并显示新闻标题,这个例子使用了[天行数据](https://www.tianapi.com/)提供的国内新闻数据接口,其中的APIKey需要自己到该网站申请。

```Python
import requests
import json


def main():
resp = requests.get('http://api.tianapi.com/guonei/?key=APIKey&num=10')
data_model = json.loads(resp.text)
for news in data_model['newslist']:
print(news['title'])


if __name__ == '__main__':
main()
```
20 changes: 20 additions & 0 deletions Jax_code/Day12/Code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import re

pattern = re.compile(r'(?<=\D)1[34578]\d{9}(?=\D)')
sentence = '''
重要的事情说8130123456789遍,我的手机号是13512346789这个靓号,
不是15600998765,也是110或119,王大锤的手机号才是15600998765。
'''
# 查找所有匹配并保存到一个列表中
mylist = re.findall(pattern, sentence)
print(mylist)
print('--------华丽的分隔线--------')
# 通过迭代器取出匹配对象并获得匹配的内容
for temp in pattern.finditer(sentence):
print(temp.group())
print('--------华丽的分隔线--------')
# 通过search函数指定搜索位置找出所有匹配
m = pattern.search(sentence)
while m:
print(m.group())
m = pattern.search(sentence, m.end())
60 changes: 60 additions & 0 deletions Jax_code/Day12/Note.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#### 正则表达式
| 符号 | 解释 | 示例 | 说明 |
| ------------------ | ----------------------------------------- | ---------------- | -------------------------------------------------- |
| . | 匹配任意字符 | b.t | 可以匹配bat / but / b#t / b1t等 |
| \\w | 匹配字母/数字/下划线 | b\\wt | 可以匹配bat / b1t / b_t等<br>但不能匹配b#t |
| \\s | 匹配空白字符(包括\r、\n、\t等) | love\\syou | 可以匹配love you |
| \\d | 匹配数字 | \\d\\d | 可以匹配01 / 23 / 99等 |
| \\b | 匹配单词的边界 | \\bThe\\b | |
| ^ | 匹配字符串的开始 | ^The | 可以匹配The开头的字符串 |
| $ | 匹配字符串的结束 | .exe$ | 可以匹配.exe结尾的字符串 |
| \\W | 匹配非字母/数字/下划线 | b\\Wt | 可以匹配b#t / b@t等<br>但不能匹配but / b1t / b_t等 |
| \\S | 匹配非空白字符 | love\\Syou | 可以匹配love#you等<br>但不能匹配love you |
| \\D | 匹配非数字 | \\d\\D | 可以匹配9a / 3# / 0F等 |
| \\B | 匹配非单词边界 | \\Bio\\B | |
| [] | 匹配来自字符集的任意单一字符 | [aeiou] | 可以匹配任一元音字母字符 |
| [^] | 匹配不在字符集中的任意单一字符 | [^aeiou] | 可以匹配任一非元音字母字符 |
| * | 匹配0次或多次 | \\w* | |
| + | 匹配1次或多次 | \\w+ | |
| ? | 匹配0次或1次 | \\w? | |
| {N} | 匹配N次 | \\w{3} | |
| {M,} | 匹配至少M次 | \\w{3,} | |
| {M,N} | 匹配至少M次至多N次 | \\w{3,6} | |
| \| | 分支 | foo\|bar | 可以匹配foo或者bar |
| (?#) | 注释 | | |
| (exp) | 匹配exp并捕获到自动命名的组中 | | |
| (?&lt;name&gt;exp) | 匹配exp并捕获到名为name的组中 | | |
| (?:exp) | 匹配exp但是不捕获匹配的文本 | | |
| (?=exp) | 匹配exp前面的位置 | \\b\\w+(?=ing) | 可以匹配I'm dancing中的danc |
| (?<=exp) | 匹配exp后面的位置 | (?<=\\bdanc)\\w+\\b | 可以匹配I love dancing and reading中的第一个ing |
| (?!exp) | 匹配后面不是exp的位置 | | |
| (?<!exp) | 匹配前面不是exp的位置 | | |
| *? | 重复任意次,但尽可能少重复 | a.\*b<br>a.\*?b | 将正则表达式应用于aabab,前者会匹配整个字符串aabab,后者会匹配aab和ab两个字符串 |
| +? | 重复1次或多次,但尽可能少重复 | | |
| ?? | 重复0次或1次,但尽可能少重复 | | |
| {M,N}? | 重复M到N次,但尽可能少重复 | | |
| {M,}? | 重复M次以上,但尽可能少重复 | | |

> **说明:** 如果需要匹配的字符是正则表达式中的特殊字符,那么可以使用\\进行转义处理,例如想匹配小数点可以写成\\.就可以了,因为直接写.会匹配任意字符;同理,想匹配圆括号必须写成\\(和\\),否则圆括号被视为正则表达式中的分组。

### Python对正则表达式的支持

Python提供了re模块来支持正则表达式相关操作,下面是re模块中的核心函数。

| 函数 | 说明 |
| -------------------------------------------- | ------------------------------------------------------------ |
| compile(pattern, flags=0) | 编译正则表达式返回正则表达式对象 |
| match(pattern, string, flags=0) | 用正则表达式匹配字符串 成功返回匹配对象 否则返回None |
| search(pattern, string, flags=0) | 搜索字符串中第一次出现正则表达式的模式 成功返回匹配对象 否则返回None |
| split(pattern, string, maxsplit=0, flags=0) | 用正则表达式指定的模式分隔符拆分字符串 返回列表 |
| sub(pattern, repl, string, count=0, flags=0) | 用指定的字符串替换原字符串中与正则表达式匹配的模式 可以用count指定替换的次数 |
| fullmatch(pattern, string, flags=0) | match函数的完全匹配(从字符串开头到结尾)版本 |
| findall(pattern, string, flags=0) | 查找字符串所有与正则表达式匹配的模式 返回字符串的列表 |
| finditer(pattern, string, flags=0) | 查找字符串所有与正则表达式匹配的模式 返回一个迭代器 |
| purge() | 清除隐式编译的正则表达式的缓存 |
| re.I / re.IGNORECASE | 忽略大小写匹配标记 |
| re.M / re.MULTILINE | 多行匹配标记 |

> **说明:** 上面提到的re模块中的这些函数,实际开发中也可以用正则表达式对象的方法替代对这些函数的使用,如果一个正则表达式需要重复的使用,那么先通过compile函数编译正则表达式并创建出正则表达式对象无疑是更为明智的选择。

### 爬虫专家必备 正则表达式
Empty file added Jax_code/Day13/Code.py
Empty file.
Empty file added Jax_code/Day13/Note.md
Empty file.
Empty file added Jax_code/Day14/Code.py
Empty file.
Empty file added Jax_code/Day14/Note.md
Empty file.
Empty file added Jax_code/Day15/Code.py
Empty file.
Empty file added Jax_code/Day15/Note.md
Empty file.
3 changes: 3 additions & 0 deletions Jax_code/Day2/Code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
a = int(input("a = \n"))
b = int(input("b = \n"))
print('%d + %d = %d' % (a, b, a+b))
45 changes: 45 additions & 0 deletions Jax_code/Day2/Note.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#### 变量命名

对于每个变量我们需要给它取一个名字,就如同我们每个人都有属于自己的响亮的名字一样。在Python中,变量命名需要遵循以下这些必须遵守硬性规则和强烈建议遵守的非硬性规则。

- 硬性规则:
- 变量名由字母(广义的Unicode字符,不包括特殊字符)、数字和下划线构成,数字不能开头。
- 大小写敏感(大写的`a`和小写的`A`是两个不同的变量)。
- 不要跟关键字(有特殊含义的单词,后面会讲到)和系统保留字(如函数、模块等的名字)冲突。
- PEP 8要求:
- 用小写字母拼写,多个单词用下划线连接。
- 受保护的实例属性用单个下划线开头(后面会讲到)。
- 私有的实例属性用两个下划线开头(后面会讲到)。

#### 强制转换
- `int()`:将一个数值或字符串转换成整数,可以指定进制。
- `float()`:将一个字符串转换成浮点数。
- `str()`:将指定的对象转换成字符串形式,可以指定编码。
- `chr()`:将整数转换成该编码对应的字符串(一个字符)。
- `ord()`:将字符串(一个字符)转换成对应的编码(整数)。

#### 简单的计算和转换
a = int(input('a = '))
b = int(input('b = '))
print('%d + %d = %d' % (a, b, a + b))

#### 运算符

Python支持多种运算符,下表大致按照优先级从高到低的顺序列出了所有的运算符,运算符的优先级指的是多个运算符同时出现时,先做什么运算然后再做什么运算。除了我们之前已经用过的赋值运算符和算术运算符,我们稍后会陆续讲到其他运算符的使用。

| 运算符 | 描述 |
| ------------------------------------------------------------ | ------------------------------ |
| `[]` `[:]` | 下标,切片 |
| `**` | 指数 |
| `~` `+` `-` | 按位取反, 正负号 |
| `*` `/` `%` `//` | 乘,除,模,整除 |
| `+` `-` | 加,减 |
| `>>` `<<` | 右移,左移 |
| `&` | 按位与 |
| `^` `\|` | 按位异或,按位或 |
| `<=` `<` `>` `>=` | 小于等于,小于,大于,大于等于 |
| `==` `!=` | 等于,不等于 |
| `is` `is not` | 身份运算符 |
| `in` `not in` | 成员运算符 |
| `not` `or` `and` | 逻辑运算符 |
| `=` `+=` `-=` `*=` `/=` `%=` `//=` `**=` `&=` `|=` `^=` `>>=` `<<=` | (复合)赋值运算符 |
9 changes: 9 additions & 0 deletions Jax_code/Day3/Code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
else:
if x >= -1:
y = x + 2
else:
y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))
1 change: 1 addition & 0 deletions Jax_code/Day3/Note.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#### Nothing hard to memorize
25 changes: 25 additions & 0 deletions Jax_code/Day4/Code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import random

# %%
answer = random.randint(1, 101)
counter = 0

while True:
counter += 1
guess = input("What's your guess: \n")
try:
if int(guess) == answer:
print(f"Bingo!\nYou've taken {counter} times to guess.")

break
elif int(guess) < answer:
print("Bigger!\n")
elif int(guess) > 100:
print("Too Big! Smaller than 100.\n")
else:
print("Smaller!\n")
except:
print('input not valid, wasted a chance\n')


# %%
1 change: 1 addition & 0 deletions Jax_code/Day4/Note.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#### No big deal
33 changes: 33 additions & 0 deletions Jax_code/Day5/Code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from random import randint

money = 1000
while money > 0:
print('你的总资产为:', money)
needs_go_on = False
while True:
debt = int(input('请下注: '))
if 0 < debt <= money:
break
first = randint(1, 6) + randint(1, 6)
print('玩家摇出了%d点' % first)
if first == 7 or first == 11:
print('玩家胜!')
money += debt
elif first == 2 or first == 3 or first == 12:
print('庄家胜!')
money -= debt
else:
needs_go_on = True
while needs_go_on:
needs_go_on = False
current = randint(1, 6) + randint(1, 6)
print('玩家摇出了%d点' % current)
if current == 7:
print('庄家胜')
money -= debt
elif current == first:
print('玩家胜')
money += debt
else:
needs_go_on = True
print('你破产了, 游戏结束!')
1 change: 1 addition & 0 deletions Jax_code/Day5/Note.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#### Still no big deal
28 changes: 28 additions & 0 deletions Jax_code/Day6/Code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# %%
from regex import B
from sympy import N
import Code2

print("Lee called")

# %%
def foo():
global a
a = 200 #全局作用域
b = 100 #嵌套作用域

def bar():
nonlocal b
global c
b = 200
c = 200
bar()
print(b)

if __name__ == '__main__':
a = 100
c = 100

foo()
print(a, c)
# %%
6 changes: 6 additions & 0 deletions Jax_code/Day6/Code2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
def foo():
print("Foo called")


if __name__ == '__main__':
print("Bar called")
Loading