Python三部曲

简介:

anaconda3下载地址

官网:https://www.anaconda.com/download/
百度云链接:https://pan.baidu.com/s/17jHeU909P1pmITCkZg3tcQ 密码:javt

python基础语法文档

官网:https://docs.python.org/3.6/tutorial/index.html

为什么要使用python

一、python调试非常简单的解释性语言
二、跨平台
三、广泛的应用编程接口
四、丰富的开源包

Python编辑器下载:https://www.jetbrains.com/pycharm/
破解介绍(该网址注册码已过期):https://blog.csdn.net/px41834/article/details/79256024/
注册码:

K71U8DBPNE-eyJsaWNlbnNlSWQiOiJLNzFVOERCUE5FIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZWVOYW1lIjoiIiwiYXNzaWduZWVFbWFpbCI6IiIsImxpY2Vuc2VSZXN0cmljdGlvbiI6IkZvciBlZHVjYXRpb25hbCB1c2Ugb25seSIsImNoZWNrQ29uY3VycmVudFVzZSI6ZmFsc2UsInByb2R1Y3RzIjpbeyJjb2RlIjoiSUkiLCJwYWlkVXBUbyI6IjIwMTktMDUtMDQifSx7ImNvZGUiOiJSUzAiLCJwYWlkVXBUbyI6IjIwMTktMDUtMDQifSx7ImNvZGUiOiJXUyIsInBhaWRVcFRvIjoiMjAxOS0wNS0wNCJ9LHsiY29kZSI6IlJEIiwicGFpZFVwVG8iOiIyMDE5LTA1LTA0In0seyJjb2RlIjoiUkMiLCJwYWlkVXBUbyI6IjIwMTktMDUtMDQifSx7ImNvZGUiOiJEQyIsInBhaWRVcFRvIjoiMjAxOS0wNS0wNCJ9LHsiY29kZSI6IkRCIiwicGFpZFVwVG8iOiIyMDE5LTA1LTA0In0seyJjb2RlIjoiUk0iLCJwYWlkVXBUbyI6IjIwMTktMDUtMDQifSx7ImNvZGUiOiJETSIsInBhaWRVcFRvIjoiMjAxOS0wNS0wNCJ9LHsiY29kZSI6IkFDIiwicGFpZFVwVG8iOiIyMDE5LTA1LTA0In0seyJjb2RlIjoiRFBOIiwicGFpZFVwVG8iOiIyMDE5LTA1LTA0In0seyJjb2RlIjoiR08iL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5bq23VmIqqDLgkNzuoog==

Python常用命令介绍:

#!/usr/bin/pyhon3
#if条件语句
# x = int(input("Please enter an integer: "))
# if x < 0:
#     x = 0
#     print('Negative changed to zero')
# elif x == 0:
#     print('Zero')
# elif x == 1:
#     print("single")
# else:
#     print('More')
 
#for循环语句
words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w, len(w))
 
#range()函数
print(range(5))
#[0, 1, 2, 3, 4]
print(list(range(5)))
for i in range(5):
    print(i)
#range的等差数列
print(list(range(0, 10, 3)))
print(list(range(-10, -100, -30)))
#取10以内的质数的程序
for n in range(2, 10):
     for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
     else:
            # loop fell through without finding a factor
        print(n, 'is a prime number')
 
#定义一个函数  计算斐波那契额
#把我们重复的计算劳动封装成一个函数,来减少工作
#def关键字是定义函数的,后面必须跟着函数名和包括形式参数的圆括号,
#它的下一行必须是缩进
def fib(n):    # write Fibonacci series up to n
     """Print a Fibonacci series up to n."""
     a, b = 0, 1
     while a < n:
         print(a, end=' ')
         a, b = b, a+b
     print()
fib(100)
#我们之前写的都是直接print的,现在,我想获得运行的结果,而不是打印
def fib2(n):  # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    result = []
    while a < n:
        result.append(a)
        a, b = b, a + b
    return result
fibresult = fib2(20)
print(fibresult)
 
#Default Argument Values  默认参数值
#四个参数,一个没有默认值,另外两个有
def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)
#w我们函数调用之传入了一个值
print(ask_ok('Do you really want to quit?'))
print(ask_ok('Do you really want to quit?',retries=1))
#ask_ok() missing 1 required positional argument: 'prompt'
print(ask_ok())
#没有默认值的一定要传参数,否则会报错,有默认值的可以不传参数,因为有默认值
#后面我们进行机器学习算法调优的时候会用到,因为,默认的算法都带有默认的参数,
#但是这个参数不是最优,要根据我们的实际情况来选择参数
#!/usr/bin/pyhon3
#这是我的第一个python
# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
print(spam)
print(text)
#python中,将所有除返回的类型都是float(带小数点的)
print(type((50 - 5*6) / 4))
#如果我们就想要返回一个整数
print(((50 - 5*6) // 4))
#取余
print(17 % 3)
print(5 * 3 + 2)
#python做幂的运算
print(5**2)
print(2**7)
print(pow(5,2))
print(pow(2,7))
#进行简单的赋值操作
w = 20
h = 50
print(w*h)
#第一个报错,未定义的错
# NameError: name 'n' is not defined
#print(n)
# int a;默认是0
 
#float类型和int类型混合运算,会转化为float
print(4 * 3.75 - 1)
#和java不同,这里能编译过,表示3个‘aaaa’
print(3*"aaaa")
#Str类型
print("ruozei")
#转义符号
print('ruo\'zei')
print("\"Yes,\" they said.")
#这里需要注意一下,python中,\u 表示后面的都是unicode编码
#加一个字母r 来让我们的转义无效
print(r"C:\Users\11725\PycharmProjects\pythonLearning\ruozei-python\__init__.py")
print(r"first line \n second line")
#多行字符串的问题
#加\ 表示这一行还没有结束,后面还有内容
print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")
#字符串拼接
print(3 * 'un' + 'ium')
print('py'  'thon')
#变量和字符串直接拼接是不行的,要加上+好
prefix = 'Py'
#invalid syntax
#print(prefix  'thon')
print(prefix+'thon')
#python数组的一些内容
word = 'Python'
print(word[0])
print(word[5])
#如果我填写了超过字符串长度的索引
#IndexError: string index out of range
#print(word[6])
#从后往前的索引
print(word[-1])
#区别,正索引是0到5   负索引是-1 到-6
 
#python还支持切片的操作
#我们想取 0和1  但是,我们要写到2
print(word[0:2])
#在索引中加入':',':'之前的,默认从0开始
#':'后面的,默认是到最后字符
print(word[:2])
print(word[2:])
print(word[:])
#
#  +---+---+---+---+---+---+
#  | P | y | t | h | o | n |
#  +---+---+---+---+---+---+
#  0   1   2   3   4   5   6
# -6  -5  -4  -3  -2  -1
print(word[4:42])
print(word[42:])
#我们不能把字符串的内容取出来重新复制
#TypeError: 'str' object does not support item assignment
#报的错要注释,否则,编译会卡在这里,进行不到下面
#word[0] = 'j'
#但是支持取出里面的内容,重新组成字符串
print('J' + word[1:])
print(len(word))
#python列表
squares = [1, 4, 9, 16, 25]
print(squares)
print(squares[0])
print(squares[-1])
#列表可以和其他列表相加
print(squares + [36, 49, 64, 81, 100])
#列表是支持重新赋值
squares[0] = 121
print(squares)
#列表添加元素 列表不需要类型一致
squares.append('aaa')
print(squares)
#其他操作
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters[2:5] = []
print(letters)
letters[:] = []
print(letters)
#两个列表结合
a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
print(x[0][1])
 
##First Steps Towards Programming
#换行的话,加':',下一行前面是tab空格符
a,b = 0,1
while b<100:
    print(b)
    a, b = b, a + b
i = 100
print('The value of i is',i)

现阶段主要是熟悉Python的各种定义,方法等等,以下是课程中老师所写的代码示范+笔记:

0

#列表
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
# #统计列表元素
print(fruits.count('apple'))
# #索引列表元素
print(fruits.index('banana'))
#反转列表
fruits.reverse()
print(fruits)
#按照字典顺序排序
fruits.sort()
print(fruits)
print(fruits.pop())
print(fruits)
 
vec = [-4, -2, 0, 2, 4]
vec1 = [x*2 for x in vec]
print(vec1)
from math import pi
pi_list = [str(round(pi, i)) for i in range(1, 6)]
print(pi_list)
 
#del和pop的区别
#del是直接删除元素,没有返回值,pop则有返回值
del fruits[0]
print(fruits.pop())
print(fruits)
#元祖
t = 12345, 54321, 'hello!'
# print(t[0])
# 'tuple' object does not support item assignment
#元祖和string的index一样,不能被改变
#t[0] = 88888
v = ([1, 2, 3], [3, 2, 1])
# print(v[0][1])
#
# x,y,z = t
# print(x,y,z)
 
#sets集合  无序的 不重复的
# A set is an unordered collection with no duplicate elements.
#第一种定义方法,直接一个大括号
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)
#第二种定义方法
a = set('abracadabra')
print(a)
 
#字典  和java的map有点类似
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print(tel)
print(list(tel.keys()))
print(sorted(tel.keys()))
#生成字典的方式
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{x: x**2 for x in (2, 4, 6)}
dict(sape=4139, guido=4127, jack=4098)
 
#遍历字典
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
   print(k+":"+v)
 
#两个返回值  一个是索引,另外一个才是value
for i, v in enumerate(['tic', 'tac', 'toe']):
   print(i, v)
#同时对两个列表进行遍历
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
   print('What is your {0}?  It is {1}.'.format(q, a))
 
#python运行时传参

1

#ZeroDivisionError
#print(1/0)
import sys
 
try:
    #我们读一个文件的时候,可能这个文件并不存在,这个时候会有异常
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
 
def divide(x, y):
   try:
     result = x / y
   except Exception:
       print("erro")
   else:
     print("result is", result)
   finally:
     print("executing finally clause")
divide(2, 1)
divide(2, 0)
divide("2", "1")

2

#The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter
s = 'Hello, world.'
print(str(s))
print(repr(s))
#字符串的标准输入输出
print('We are the '+'knights'+' who say "'+'Ni'+'!"')
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))
import math
#输出三位小数
print('The value of PI is approximately {0:.3f}.'.format(math.pi))
 
#python io流
#mode can be 'r' when the file will only be read, 'w' for only writing
#'a' opens the file for appending
# f = open('workfile', 'w')
# f.write("this is ruoze data for python")
# f = open('workfile', 'r')
# print(f.read())
# f = open('workfile', 'a')
# f.write("this is ruoze data for python\n")
# f.close()
#我们进行io流的时候,要记得关闭资源
f = open('workfile', 'r')
print(f.readline())
print(f.readline())

3

#!/usr/bin/pyhon3
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")
parrot(1000)
print("---------------------华丽的分割线-----------")
parrot(voltage=1000)
print("---------------------华丽的分割线-----------")
#传给默认参数一个值,会覆盖掉原来的值
parrot(voltage=1000000, action='VOOOOOM')
print("---------------------华丽的分割线-----------")
parrot(action='VOOOOOM', voltage=1000000)
print("---------------------华丽的分割线-----------")
#如果参数都没有key,就按照函数传入参数的顺序来
parrot('a million', 'bereft of life', 'jump')
 
#接下来就是错误的演示
#dTypeError: parrot() missing 1 require positional argument: 'voltage'
#因为,第一参数没有默认值,所以一定要传入
#parrot()
#non-keyword argument after a keyword argument
#在keyword参数后面,不能传non-keyword
#parrot(voltage=5.0, 'dead')
 
#TypeError: parrot() got multiple values for argument 'voltage'
#parrot(110, voltage=220)
 
#TypeError: parrot() got an unexpected keyword argument 'actor'
#parrot(actor='John Cleese')
 
#如果我们需要传入n多个参数,或者是n多keyword参数
#*arguments可以传入多个单值参数
#**keywords可以传入多个keyvalue参数
def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])
 
 
cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")
 
#Lambda Expressions
def make_incrementor(n):
    return lambda x: x + n
f = make_incrementor(42)
print(f(0))
 
lambda_list = [1,2,3,4,5,6,7,8]
 
#map函数,就是对列表中每一个元素进行操作
map_lambda = map(lambda a:a+10,lambda_list)
print(list(map_lambda))
filter_lambda = filter(lambda b:b>6,lambda_list)
print(list(filter_lambda))
 
 
#python doc
#加\表示这一行还没有结束
def my_function():
    """\
    Do nothing, but document it.
    No, really, it doesn't do anything.
    """
    pass
print(my_function.__doc__)

爬取的是盗版网的“免费”小说《三寸人间》(阅读小说请支持正版)

以下是源代码:

from urllib import request
from bs4 import BeautifulSoup
import re
 
//获取html源码
response=request.urlopen("http://www.biquge.com.tw/14_14055/")
html = response.read()
//解析html
soup = BeautifulSoup(html,"html.parser")
//通过正则匹配找到需要的超链接
all_href = soup.find_all(href=re.compile("^/14_14055/"))
//分割获取到的语句,取出标题和超链接
all_href_name = str(all_href).split(",")
//定义字典,把标题和超链接当作key,value
all_href_name_dict = {}
for each_href in all_href_name:
    soup_href = BeautifulSoup(each_href,"html.parser")
    key = soup_href.a["href"]
    value = soup_href.get_text()
    all_href_name_dict[key] = value
print(all_href_name_dict)
# del all_href_name_dict['/14_14055/']
 
//获取html源码
def get_html(url):
    response = request.urlopen(url)
    html = response.read()
    return html
//解析源码,获取小说内容
def get_content(url):
    content_html = get_html(url)
    soup = BeautifulSoup(content_html,"html.parser")
    txt_show = soup.find_all('div',attrs={'id':'content'})
    return txt_show[0]
//把小说写进本地txt文本
def write_to_txt(context,title):
    with open('sancunrenjian','a',encoding='utf-8')as f:
        f.write('\n'+title+'\n'+context)
//开始执行
for k,v in all_href_name_dict.items():
    charpter_url="http://www.biquge.com.tw"+k
    print(charpter_url)
    charpter_txt = get_content(charpter_url)
//把不需要的内容替换掉
    txt = str(charpter_txt).replace("<div id=\"content\">","").replace("<br/>","").replace("</div>","")
    write_to_txt(str(txt),v)

部分操作结果:

在这里插入图片描述

原文连接
https://blog.csdn.net/qq_37408712/article/details/81466805

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

脸ル粉嘟嘟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值