python 编程

例子1:
python获取手机分辨率并返回
 
import os
import sys
import re
 
 
def _get_screen_size():
    '获取手机屏幕大小'
    size_str = os.popen('adb shell wm size').read()
    if not size_str:
        print('请安装 ADB 及驱动并配置环境变量')
        sys.exit()
    m = re.search(r'(\d+)x(\d+)', size_str)
    if m:
        return "{height}x{width}".format(height=m.group(2), width=m.group(1))
    return "1920x10"
 
print(_get_screen_size())
 
 
例子2:
 
输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
importstring
s=raw_input('input a string:\n')
letters=0
space=0
digit=0
others=0
forcins: ####字符串是可迭代的
   ifc.isalpha():
       letters+=1
   elifc.isspace():
       space+=1
   elifc.isdigit():
       digit+=1
   else:
       others+=1
print'char = %d,space = %d,digit = %d,others = %d'%(letters,space,digit,others)
 
 
例子3: 统计一句话中每个单词出现的次数
str1 = "Man who run in front of car, get tired.Man who run behind car, get exhausted."
#str1 = input("请输入要查询的字符:")

worldList1 = str1.split()
worldList2 = []
worldDict3 = {}

print(worldList1)

for word1 in worldList1:
lastchar = word1[-1:]
if lastchar in [",",".","!","?",":"]:
word2 = word1.rstrip(lastchar)
else:
word2 = word1
worldList2.append(word2.lower())
print(worldList2)

for word2 in worldList2:
worldDict3[word2] = worldDict3.get(word2,0)+1


keyList = worldDict3.keys()
print(keyList)
for key in keyList:
print ("%-10s %d" % (key, worldDict3[key]))

例子4:统计出每个IP的访问量有多少?(从日志文件中查找)
#!/usr/bin/env python
#!coding=utf-8
list = []
f = file('/tmp/1.log')
str1 = f.readlines() 
f.close() 
for i in str1:
    ip =  i.split()[0]
    list.append(ip) 
list_num = set(list)
for j in list_num: 
    num = list.count(j) 
    print '%s : %s' %(j,num)
例子5:如何判断一个字符串是回文字符串,并对你的写出的方法进行测试
    
def func(str):
    if not isinstance(str,basestring):
        print "{} 不是字符串类型 ".format(str)
    elif len(str)-1<=0:
        print "{} is not 回文字符串".format(str)
    else:
        i=0
        j=len(str)-1
        while i<j:
            if str[i]!=str[j]:
                break
            i+=1
            j-=1
        if i<j:
            print "{} is not 回文字符串".format(str)
        else:
            print "{} is 回文字符串".format(str)
 
 
posted @ 2018-07-26 17:03  lillianli  阅读(197)  评论(0)    收藏  举报