简单代码片段
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")
continue
print("nono")
print("good")
if s == 'quit':
break
print('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":
break
if len(s)<3:
print("too small")
continue
print("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]+i
files.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=0
beg=0
num1=0
while i<len(con):
if num1>=0:
num1=con.find('title="[博海拾贝',beg)
else:
break
num2=con.find(' - 博海拾贝" target',num1)
if num1>=0:
title_list.append(con[num1+17:num2])
beg=num2
i+=100
return 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 = temp
print('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.0
b = 1.0 / math.sqrt(2)
t = 1.0 / 4.0
p = 1.0
for i in range(1,9):
at = (a + b) / 2
bt = math.sqrt(a * b)
tt = t - p * (a - at) ** 2
pt = 2 * p
a = at; b = bt; t = tt; p = pt
my_pi = (a + b) ** 2 / (4 * t)
accuracy = 100 * (math.pi - my_pi) / my_pi
print("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 glob
class PowerShell:
# from scapy
def __init__(self, coding, ):
cmd = [self._where('PowerShell.exe'),
"-NoLogo", "-NonInteractive", # Do not print headers
"-Command", "-"] # Listen commands from stdin
startupinfo = sp.STARTUPINFO()
startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW
self.popen = sp.Popen(cmd, stdout=sp.PIPE, stdin=sp.PIPE, stderr=sp.STDOUT, startupinfo=startupinfo)
self.coding = coding
def __enter__(self):
return self
def __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
@staticmethod
def _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 filename
paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs
try:
return next(os.path.normpath(match)
for path in paths
for 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]+=1
y[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]]]