简单代码片段

2的n次方,猜数字,压缩文件并输出,简单爬标题

import random
import sys
import os
import time
import zipfile
import requests,json#2的n次方,10以内
while i in range(1,10):print(2<<i)i+=1#猜数字
while True:s = input('Enter something : ')if len(s)<3:print("nss")continueprint("nono")print("good")if s == 'quit':breakprint('Length of the string is', len(s))
print('Done')while 1>0:g = int(input('guess :'))d = random.randint(1 , 100)if g<d:print("low")elif g>d:print("high")else:print("done")break
print("good")while True:s = input("enter:")if s=="quit":breakif len(s)<3:print("too small")continueprint("good")#压缩文件并输出保存
source = ['d:\\888\\','d:\\7798\\']target_dir = ['d:\\888back']
'''
target = target_dir+os.sep+ \time.strftime('%Y%m%d')+'.zip'
if not os.path.exists(target_dir):os.mkdir(target_dir)
zip_command= 'zip -r {0} {1}'.format(target,' '.join(source))
print('zip command is: \n',zip_command)
print('running:')
if os.system(zip_command)==0:print('ok')
else:print('error')
'''def zip_files(files,zip_name):zip= zipfile.ZipFile(zip_name,'w',zipfile.ZIP_DEFLATED)for file in files:print('compressing',file)zip.write(file)zip.close()print('ok')
files=[]
for i in os.listdir('d:\\888\\'):i=source[0]+ifiles.append(i)print(files)#files=['d:\\888\a.docx','d:\\888\b.xlsx']
zip_file='d:\\888back\\123.zip'
zip_files(files,zip_file)#简单爬标题
if __name__ == '__main__':target = 'https://bh.sb/post/category/main/'requests.packages.urllib3.disable_warnings()req = requests.get(url=target,verify=False)
def content(html):# 内容分割的标签str = '<article class="excerpt excerpt-one">'content = html.partition(str)[2]str1 = '<aside class="sidebar">'content = content.partition(str1)[0]return content # 得到网页的内容str0=content(str(req.content,encoding='UTF-8'))
#print(str0)def cut1(con):title_list=[]i=0beg=0num1=0while i<len(con):if num1>=0:num1=con.find('title="[博海拾贝',beg)else:breaknum2=con.find(' - 博海拾贝" target',num1)if num1>=0:title_list.append(con[num1+17:num2])beg=num2i+=100return title_list#str1=cut1(str0)
print(cut1(str0))#print('asdf=adm'.split('a')[-2])#str1='aa-bb-cc'
#print(str1.partition('-'))##print(str(req.content,encoding='UTF-8').partition('<excerpt excerpt-one">'))

获得文本拼音首字母

from xpinyin import Pinyin
import os
import sys
#获得文本拼音首字母
f = open("d:/1.txt","r")
txt =f.readlines()
print(txt)
f.close()
f = open("d:/1.txt","r")
line = f.readline()
line = line[:-1]
print(line)
while line:line =f.readline()line = line[:-1]print(line)
f.close()data=[]
for lines in open("d:/1.txt","r"):data.append(lines[:-1])
print(data)p=Pinyin()for i in  data:print(Pinyin().get_pinyin(i).title())

转移输出(这个我也没看懂)

#spam 123移到了 back here 后面
g,h,j=1,2,30
print(g,h,j)
temp = sys.stdout
sys.stdout = open('log.txt','w')
print('spam')
print(1,2,3)
sys.stdout.close()
sys.stdout = tempprint('back here')
print(open('log.txt').read())

pi的计算,ps脚本

import sys
import math
#print(math.pi)#from math import pi
#print(pi)
#pi的计算
def main(argv):
#    if len(argv) != 1 :#       sys.exit('Usage: calc_pi.py <n>')print('\nComputing Pi v.01\n')a = 1.0b = 1.0 / math.sqrt(2)t = 1.0 / 4.0p = 1.0for i in range(1,9):at = (a + b) / 2bt = math.sqrt(a * b)tt = t - p * (a - at) ** 2pt = 2 * pa = at;        b = bt;        t = tt;        p = ptmy_pi = (a + b) ** 2 / (4 * t)accuracy = 100 * (math.pi - my_pi) / my_piprint("Pi is approximately: " + str(my_pi))print("Accuracy with math.pi: " + str(accuracy))
main(sys.argv[1:9])#ps脚本
import os
import subprocess as sp
from glob import globclass PowerShell:# from scapydef __init__(self, coding, ):cmd = [self._where('PowerShell.exe'),"-NoLogo", "-NonInteractive",  # Do not print headers"-Command", "-"]  # Listen commands from stdinstartupinfo = sp.STARTUPINFO()startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOWself.popen = sp.Popen(cmd, stdout=sp.PIPE, stdin=sp.PIPE, stderr=sp.STDOUT, startupinfo=startupinfo)self.coding = codingdef __enter__(self):return selfdef __exit__(self, a, b, c):self.popen.kill()def run(self, cmd, timeout=15):b_cmd = cmd.encode(encoding=self.coding)try:b_outs, errs = self.popen.communicate(b_cmd, timeout=timeout)except sp.TimeoutExpired:self.popen.kill()b_outs, errs = self.popen.communicate()outs = b_outs.decode(encoding=self.coding)return outs, errs@staticmethoddef _where(filename, dirs=None, env="PATH"):"""Find file in current dir, in deep_lookup cache or in system path"""if dirs is None:dirs = []if not isinstance(dirs, list):dirs = [dirs]if glob(filename):return filenamepaths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirstry:return next(os.path.normpath(match)for path in pathsfor match in glob(os.path.join(path, filename))if match)except (StopIteration, RuntimeError):raise IOError("File not found: %s" % filename)if __name__ == '__main__':# Example:def run(a):with PowerShell('GBK') as ps:outs, errs = ps.run(a)print('error:', os.linesep, errs)print('output:', os.linesep, outs)run('get-process powershell')

简单算法

计算某字串重复字符及数量及位置

def choselongstr(a):x=list(str(a))y=[]z=[]for i in range(0,len(x)):if i==0:y.append([x[i],1,[i+1]])z.append(x[i])if i>0:for j in range(0,len(y)):if x[i]==str(y[j][0]):y[j][1]+=1y[j][2].append(i+1)elif x[i]!=str(y[j][0]) and j==(len(y)-1):if x[i] not in z:y.append([x[i],1,[i+1]])z.append(x[i])print(y)choselongstr(522311276522)
#######################################
#[['5', 2, [1, 10]], ['2', 5, [2, 3, 7, 11, 12]], ['3', 1, [4]], ['1', 2, [5, 6]], ['7', 1, [8]], ['6', 1, [9]]]

python学习笔记4-简单代码相关推荐

  1. 【Python学习笔记】简单调用百度API应用

    #本文一切代码及理论均来自于郑秋生.夏敏捷二位老师主编<Python项目案例发 从入门到实践>一书,本人仅做微改.创作本文的目的仅为总结本人的学习过程和成果,借此巩固.可能存在许多疏漏之处 ...

  2. python自训练神经网络_tensorflow学习笔记之简单的神经网络训练和测试

    本文实例为大家分享了用简单的神经网络来训练和测试的具体代码,供大家参考,具体内容如下 刚开始学习tf时,我们从简单的地方开始.卷积神经网络(CNN)是由简单的神经网络(NN)发展而来的,因此,我们的第 ...

  3. python学习笔记(一)Python 简单介绍

    Python学习笔记(一)Python 简单介绍 Python介绍 Python简介 Python应用领域 Python是解释型的语⾔ 编译和解释的区别是什么? 编译型vs解释型 编译型 解释型 Py ...

  4. 从滚动条到画布的几个代码文件——Python学习笔记之十七

    从滚动条到画布的几个代码文件--Python学习笔记之十七 这一章的继续学习,比在前的照片涉及代码要轻松一些,代码打完后的预期结果总能实现.特别让人欣慰的一点,文本上的文字理解好像上了一个台阶,不用多 ...

  5. Python学习笔记(十一)

    Python学习笔记(十一): 生成器,迭代器回顾 模块 作业-计算器 1. 生成器,迭代器回顾 1. 列表生成式:[x for x in range(10)] 2. 生成器 (generator o ...

  6. Python学习笔记一简介及安装配置

    Python学习笔记一 参考教程:廖雪峰官网https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e54 ...

  7. python 学习笔记 12 -- 写一个脚本获取城市天气信息

    近期在玩树莓派,前面写过一篇在树莓派上使用1602液晶显示屏,那么可以显示后最重要的就是显示什么的问题了. 最easy想到的就是显示时间啊,CPU利用率啊.IP地址之类的.那么我认为呢,假设可以显示当 ...

  8. OpenCV之Python学习笔记(1)(2): 图像的载入、显示和保存 图像元素的访问、通道分离与合并

    OpenCV之Python学习笔记 一直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看到一本国外的新书< ...

  9. Python学习笔记:Day15 部署Web App

    前言 最近在学习深度学习,已经跑出了几个模型,但Pyhton的基础不够扎实,因此,开始补习Python了,大家都推荐廖雪峰的课程,因此,开始了学习,但光学有没有用,还要和大家讨论一下,因此,写下这些帖 ...

最新文章

  1. 大佬教你极简方法来处理Android SharedPreferences设计与实现
  2. libtorch调用模型
  3. Ardino基础教程 15_火焰报警器
  4. centos7 mysql tar_CentOS7中mysql-5.7.21-el7-x86_64.tar.gz版MySQL的安装与配置
  5. post大小限制_作为一个程序员,面试中常问的get和post的区别,你真的知道吗
  6. 在Nutz中如何配置多个数据库源,并且带事务控制
  7. python软件下载教程-使用最方便的计算机编程软件,Python下载使用完美教程
  8. SPOJ REPEATS Repeats (后缀数组 + RMQ:子串的最大循环节)题解
  9. 房价增幅或于年底见顶
  10. hdu 1596 概率dijstra
  11. verilog符号 与或非 异或_与()、非(~)、或(|)、异或(^)
  12. Java图形用户界面实验
  13. cdn加速的原理及步骤
  14. 重启PocketPC移动设备
  15. 【论文阅读】Enhancing Underwater Imagery using Generative Adversarial Networks
  16. BD电影搜索-自定义过滤器
  17. nvidia driveos(Drive AGX Orin板子P3710/P3663)单独烧录kernel
  18. Win10+YOLOv4/v3用yolo_mark标记数据集 训练自己的模型
  19. java war包混淆,spring项目的代码混淆(proguard)
  20. MySQL之数据查询(多表查询)

热门文章

  1. 放大器相位裕度与电路稳定性判断方法
  2. Angular:error TS2717: Subsequent property declarations must have the same type. Property ‘contentRe
  3. BurpSuite抓https的包/BurpSuite CA证书下载
  4. Oracle经典案例
  5. pwn远程的时候遇到 timeout: the monitored command dumped core 怎么办
  6. java 用可获取的字体、样式、字号修饰文字
  7. Python中的复数类型介绍
  8. python error2_python解决方案:WindowsError: [Error 2]
  9. c语言 wifi 开发,Android WIFI Direct开发教程
  10. Caffe学习系列(十):腾讯ncnn框架