Python3自学笔记

版权声明:本文为博主原创文章,但部分内容来源自互联网,大家可以随意转载,点赞或留言均可! https://blog.csdn.net/csdn_kou/article/details/82943057

一些优秀的博主

http://blog.konghy.cn/

Python3教程

首先是掌握基本语法!

先来几个代码

str1 = input("请输入一个人的名字:")
str2 = input("请输入一个国家的名字:")
print("世界这么大,{}想去看看{}:".format(str1,str2))

1到N求和

n = input("请输入一个整数:")
sum = 0

for i in range(int(n)):
    sum += i + 1
print("1到N求和的结果:",sum)

乘法口诀表

for i in range(1,10):
    for j in range(1,i +1):
        print("{}*{}={:2}  ".format(j,i,i*j),end = '')
    print('')

打印1! + 2! + 3! + …10!

sum , tem = 0, 1
for i in range(1,4):
    print("{}".format(i))
for i in range(1,4):
    tem = i * tem
    sum += tem
print("{}".format(sum))

猴子吃桃问题!

n = 1
for i in range(5,0,-1):
    n = (n + 1) << 1
print(n)

摄氏度和华氏度温度转换

TempStr = input("")

if TempStr[0] in ['F','f']:
    C = (eval(TempStr) -32 ) /1.8
    print("{:.2f}C".format(C))
elif TempStr[0] in ['C','c']:
    F = 1.8 * eval(TempStr) + 32
    print("{:.2f}F".format(F))
else:
    print("输入格式错误")

内置的运算符函数

https://www.cnblogs.com/xiao1/p/5856890.html

math库

  • math.pi

               数学常数π= 3.141592……

  • math.e

               数学常数e = 2.718281….

  • math.tau

              数学常数τ= 6.283185……


  • math.ceil(x)

               返回x的上限,返回最小的整数A  (A>=x)。如math.ceil(3.14)返回的整数为4官网math库

  • math.fabs(x)

              返回绝对值x。

  • math.factorial(x)

              返回 x!。如果x不是积分或者是负的,就会产生ValueError

  • math.floor(x)

              返回x的下限,返回一个值最大整数A   (A<=x)如math.floor(3.14)返回的整数为3

  • math.exp(x)

        返回 ex也就是 math.e**x


  • math . pow(x,y)

              返回x的y次方,即返回 xy

  • math.sqrt(x)

              返回√x

  • math.degrees(x)

               将角x从弧度转换成角度。

  • math.radians(x)

              把角x从度转换成弧度。

  • math.acos(x)

           返回 x 的反余弦

  • math.asin(x)

           返回 x 的反正弦

  • math.atan(x)

          返回 x 的反正切。

  • math.cos(x)

            返回 x 的余弦

  • math.sin(x)

             返回 x 的正弦

  • math.tan(x)

            返回 x 的正切

  • math.log(x,a)
            返回  ,若不写a 內定 e



python官网math库链接




天天向上代码

import math
dayup = math.pow((1.0 + 0.005), 365)
daydown = math.pow((1.0 - 0.005),365)

print("向上:{:.2f},向下:{:.2f}.".format(dayup,daydown))
def dayUP(df):
    dayup = 0.01
    for i in range(365):
        if i % 7 in [6,0]:
            dayup = dayup * (1 - 0.01)
        else:
            dayup = dayup * (1 + df)
    return dayup

dayfactor = 0.01
while(dayUP(dayfactor) < 37.78):
    dayfactor += 0.001

print("每天努力参数是:{:.3f}.".format(dayfactor))

基本的字符串操作符

这里写图片描述

2.内置字符串处理函数(6个)
这里写图片描述

2.常用的内置字符串处理方法(16个)
这里写图片描述
这里写图片描述

3.特殊的格式化控制字符
这里写图片描述

4.format()方法的格式控制
这里写图片描述

random库的常用函数

在这里插入图片描述

列表类型特有的函数或方法

在这里插入图片描述

异常处理代码

try:
     <body>
except <ErrorType1>:
    <handler1>

except <ErrorType2>:
    <handler2>
except:
    <handler0>
else:
    <process_else>
finally:
    <process_finally>

单例模式

class Singleton(object):
    class _A(object):
        def __init__(self):
            pass

        def display(self):
            return id(self)
            
    _instance = None

    def __init__(self):
        if Singleton._instance is None:
            Singleton._instance = Singleton._A()

    def __getattr__(self, attr):
        return getattr(self._instance, attr)


if __name__ == '__main__':
    s1 = Singleton()
    s2 = Singleton()
    print(id(s1), s1.display())
    print(id(s2), s2.display())

代码的解释
def getattr(self, attr):
return getattr(self._instance, attr)

# 例如这里有一个类 A ,,有两个属性
>>> class A:
...     test1 = "this test1"
...     test2 = "this test2"
...
>>>

# 然后实例化一个对象
>>> a = A()

# 就可以用 getattr  直接去获取对象 a 的属性值
>>> getattr(a, "test1")
'this test1'
>>>
>>> getattr(a, "test2")
'this test2'
>>>

读写模式

https://www.cnblogs.com/c-x-m/articles/7756498.html
#1. 打开文件的模式有(默认为文本模式):
r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
w,只写模式【不可读;不存在则创建;存在则清空内容】
a, 之追加写模式【不可读;不存在则创建;存在则只追加内容】
#2. 对于非文本文件,我们只能使用b模式,“b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
rb
wb
ab
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
#”+" 表示

可以同时读写某个文件
r+, 读写【可读,可写】
w+,写读【可读,可写】
a+, 写读【可读,可写】
x, 只写模式【不可读;不存在则创建,存在则报错】
x+ ,写读【可读,可写】
xb

python读写操作的简单模板

fo = open("baidu.txt", "w+")
ls ="Hello world"
fo.write(ls)
fo.close()

如果说想把print的内容写到文件该怎么做?

fo = open("baidu.txt", "w+")
print("Hello world",file=fo)
fo.close()

python3的文本处理

jieba库的使用

pip3 install jieba

统计hamlet.txt文本中高频词的个数
讲解视频

kou@ubuntu:~/python$ cat ClaHamlet.py 
#!/usr/bin/env python
# coding=utf-8

#e10.1CalHamlet.py
def getText():
    txt = open("hamlet.txt", "r").read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")   #将文本中特殊字符替换为空格
    return txt
hamletTxt = getText()
words  = hamletTxt.split()
counts = {}
for word in words:			
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
for i in range(10):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))

统计三国演义任务高频次数

#!/usr/bin/env python
# coding=utf-8

#e10.1CalHamlet.py
def getText():
    txt = open("hamlet.txt", "r").read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")   #将文本中特殊字符替换为空格
    return txt
hamletTxt = getText()
words  = hamletTxt.split()
counts = {}
for word in words:			
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
for i in range(10):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))

Python 中的 if name == ‘main’ 该如何理解

http://blog.konghy.cn/2017/04/24/python-entry-program/

python环境搭建和pycharm的安装配置及汉化(零基础小白版)

https://blog.csdn.net/ling_mochen/article/details/79314118#commentBox

PyCharm和git安装教程

https://blog.csdn.net/csdn_kou/article/details/83720765

爬虫

学习资源是中国大学mooc的爬虫课程。《嵩天老师》
下面写几个简单的代码!熟悉这几个代码的书写以后基本可以完成需求!

简单例子1

import requests

r = requests.get("https://www.baidu.com")
fo = open("baidu.txt", "w+")
r.encoding =  'utf-8'
str = r.text
line = fo.write( str )

简单例子2

import requests
url = "https://item.jd.com/2967929.html"
try:
    r = requests.get(url)
    r.raise_for_status()//如果不是200就会报错
    r.encoding = r.apparent_encoding//转utf-8格式
    print(r.text[:1000])//只有前1000行
except:
    print("False")
 fo.close()

BeautifulSoup的使用1

fo = open("jingdong.md","w")

url = "https://item.jd.com/2967929.html"
try:
    r = requests.get(url)
    r.encoding = r.apparent_encoding
    demo = r.text
    soup = BeautifulSoup(demo,"html.parser")
    fo.write(soup.prettify())
    fo.writelines(soup.prettify())
except:
    print("False")

fo.close()

BeautifulSoup的使用1

fo = open("baidu.md","w")

try:
    r = requests.get("https://www.baidu.com")
    r.encoding = r.apparent_encoding
    demo = r.text
    soup = BeautifulSoup(demo,"html.parser")
    fo.write(soup.prettify())
    fo.writelines(soup.prettify())
except:
    print("False")
fo.close()

附赠
爬虫和python例子开源链接

猜你喜欢

转载自blog.csdn.net/csdn_kou/article/details/82943057