从编写程序中练习所学语法
import random
flag = 1
while flag:
print("你出什么?(0.石头 1.剪刀 2.布):")
y = int(input())
x = random.randint(0, 2)
if x == y:
print("x=%d y=%d" % (x, y))
print("平局~")
elif (x == 0 and y == 1) or (x == 1 and y == 2) or (x == 2 and y == 0):
print("x=%d y=%d" % (x, y))
print("你输了")
else:
print("x=%d y=%d" % (x, y))
print("你赢了")
print("再来一把?(0.不了 1.来嘛)")
flag = int(input())
for i in range(9, 0, -1):
for j in range(1, i+1):
k = i * j
if j < i:
print("%d*%d=%d" % (i, j, k), end=" ")
elif j == i:
print("%d*%d=%d" % (i, j, k))
for a in range(1, 10, 1):
for b in range(1, a+1):
k = a * b
if b < a:
print("%d*%d=%d" % (a, b, k), end=" ")
elif j == i:
print("%d*%d=%d" % (a, b, k))
products = [["iphone", 6888], ["MacPro", 14800], ["XIaoMi6", 2499], ["Coffee", 31], ["Book", 60], ["Nike", 699]]
print("------商品列表------")
for i in range(len(products)):
print("%d\t%s\t%d\t" % (i, products[i][0], products[i][1]))
flag = 1
Sum = 0
ShoppingChart = []
while flag != 'q':
print("想要购买哪件商品?")
choice = int(input())
for i in range(len(products)):
if choice == i:
print("你选择了第%d件商品\t" % i + "商品信息为:%s\t%d" % (products[i][0], products[i][1]))
ShoppingChart.append(products[i])
print("已为您加入购物车~")
break
else:
pass
print("继续选择.请按任意键 退出.请输入 q ")
flag = input()
for j in range(len(ShoppingChart)):
Sum += ShoppingChart[j][1]
print("%d\t%s\t%d\t" % (j, ShoppingChart[j][0], ShoppingChart[j][1]))
print("您购买的商品总价格为:%d" % Sum)
myList = ['a', 'b', 'c', 'd']
for i, x in enumerate(myList):
print(i+1, x)
'''
# def 函数/方法 多个返回值 return a,b 外部接收 aa,bb= 函数名
'''
def line():
print('-'*30)
line()
def lines(i):
print('-'*i)
i = int(input("请输入横线数量:"))
lines(i)
def Sum(a,b,c):
print("%d %d %d之和为:%d" % (a, b, c, a+b+c))
return a+b+c
a = 1
b = 2
c = 3
def avg(sum):
print("%d %d %d三位数和的平均值为:%f" % (a, b, c, (a+b+c)/3) )
avg(Sum(a, b, c))
```python
基本文件读写操作
import os
'''
f = open("text.txt", "w")
f.write("hello world!\n")
f.write("hello world!\n")
f.close()
f = open("text.txt", "r")
# content = f.read(10) # 读一行的10个字符
# contents = f.readline() 只读一行
contents = f.readlines() # 读所有行 以列表形式打印
print(contents)
i = 1
for j in contents:
print("%d:%s" % (i, j))
i += 1
f.close()
os.rename("text.txt", "test1.txt") # 文件重命名
'''
def Write():
f = open("gushi.txt", "w")
f.write("\t春晓\t\n春眠不觉晓,\n处处闻啼鸟。\n夜来风雨声,\n花落知多少。\n")
f.close()
def ReadAndCopy():
f = open("gushi.txt", "r")
ff = open("copy.txt", "w")
poem = f.readlines()
for i in poem:
try:
ff.write(i)
except:
pass
print(i)
print("复制完毕!")
ff = open("copy.txt", "r")
poemcopy = ff.readlines()
for k in poemcopy:
print(k)
f.close()
ff.close()
Write()
ReadAndCopy()
正则表达式相关
import re
import sys
import urllib.request
import xlwt
import bs4
import sqlite3
import urllib.parse
data = bytes(urllib.parse.urlencode({"hello": "world"}), encoding='utf-8')
response = urllib.request.urlopen("http://httpbin.org/post", data=data)
print(response.read().decode("utf-8"))
response = urllib.request.urlopen("http://www.baidu.com")
print(response.status)
print(response.getheaders())
url = "https://passport.ccf.org.cn/sso/login?from=aHR0cHM6Ly9jc3AuY2NmLm9yZy5jbi9jc3Avc2lnbnVwL3NpZ251cF9pbml0LzhhOWUzNzhlNjliN2NhMzIwMTY5YzIxMTNmY2QwMDAwLmFjdGlvbj9fYWNrPTE="
data = bytes(urllib.parse.urlencode({"hello": "world"}), encoding='utf-8')
headers = {
"User-Agent": "Mozilla/5.0 (WindowsNT10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}
req = urllib.request.Request(url=url, data=data, headers=headers, method="POST")
response = urllib.request.urlopen(req)
print(response.read().decode("UTF-8"))
'''
def main():
url = "https://movie.douban.com/top250?start="
# askURL(url)
getData(url)
def askURL(url):
headers = {
"User-Agent": "Mozilla/5.0 (WindowsNT10.0; Win64; x64)"
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}
request = urllib.request.Request(url, headers=headers)
html = "" # 字符串
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
print(html)
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e, code)
if hasattr(e, "reason"):
print(e.reason)
return html
def getData(url):
datalist = []
for i in range(0, 5):
URL = url + str(i * 25)
print("-"*100)
html = askURL(URL)
return datalist
if __name__ == '__main__':
main()
'''
from bs4 import BeautifulSoup
file = open("C:\zhengxin\google.html", "rb")
html = file.read().decode("UTF-8")
bs = BeautifulSoup(html, "html.parser")
print(bs.title)
print(bs.title.string)
print(bs.img.attrs)
print(bs.attrs)
print(bs)
print(bs.h1.contents)
T_list = bs.find_all(re.compile("l"))
print(T_list)
print("-"*50)
def id_is_exists(tag):
return tag.has_attr("id")
List = bs.find_all(id_is_exists)
for item in List:
print(item)
List = bs.find_all(id="target")
List = bs.find_all(id="target", limit=1)
for item in List:
print(item)
t_list = bs.select('h1')
t_list = bs.select('.manv')
t_list = bs.select('#target')
t_list = bs.select("a[href]")
t_list = bs.select("div > a")
t_list = bs.select(".manv ~ .bri")
print(t_list[0].get_text())
print(t_list)