Python程序设计之字符操作(字符串)

1.字符串检验密码强度密码由六位数组成
设置四种密码强弱形式:
a很弱:只包含数字、小写字母、大写字母、和标点符号中一种;
b一般:包含上述任意两种字符
c较强:包含上述任意三种字符
d很强:包含上述四种字符

import string
def check(pwd):
#密码必须至少包含6个字符
	if len(pwd)<6:
    		return 'weak'
    	d={1:'week',2:'blew middle',3:'above middle',4:'strong'}	#使用字典设置强弱对应类型
    	r=[False]*4	#需要判断用户输入字符中包含字符的种类,通过列表来判断
    	for ch in pwd:	#使用for循环遍历pwd字符串
		if not r[0] and ch in string.digits:	#遍历是否存在数字
			r[0]=True
		if not r[1] and ch in string.ascii_lowercase:	#遍历是否存在小写字母
			r[1]=True
		if not r[2] and ch in string.ascii_uppercase:	#遍历是否存在大写字母
			r[2]=True
		if not r[3] and ch in ',.|;;?<>':	#遍历是否存在指定字符
			r[3]=True
	return d.get(r.cout(True),'error')	#记录r中True的数量,并返回字典中对应的值
		
n=str(input('请输入你的密码(六位字符):'))					    			
print(check(n))	

代码链接:
https://download.csdn.net/download/qxyloveyy/12184552

2.对文件中字符串的操作
实现以下功能:
a.使用open()函数打开并读取文件中的每一行
b.重新生成一个文件,文件名是在原文件名上添加一个后缀的形式,例如原名Car.py=>Car_news.py
c.在新文件中进行写的操作,通过enumerate()遍历行数,根据字符串比较输出指定内容,例如通过strip()和startwith()函数可以实现对开头字符的判断
d.最后使用close()函数关闭文件

import sys
import re

def checkFormats(lines, desFileName):
    fp = open(desFileName, 'w')
    for i, line in enumerate(lines):
        print('=' * 30)
        print('Line:', i + 1)
        if line.strip().startswith('#'):
            print(' ' * 10 + 'Comments.Pass.')
            fp.write(line)
            continue
        flag = True
        # check operator symbols
        symbols = [',', '+', '-', '*', '/', '//', '**', '>>', '<<', '+=', '-=', '*=', '/=']
        temp_line = line
        for symbol in symbols:
            pattern = re.compile(r'\s*' + re.escape(symbol) + r'\s*')
            temp_line = pattern.split(temp_line)
            sep = ' ' + symbol + ' '
            temp_line = sep.join(temp_line)
        if line != temp_line:
            flag = False
            print(' ' * 10 + 'You may miss some blank spaces in this line.')
            # check import statement
        if line.strip().startswith('import'):
            if ',' in line:
                flag = False
                print(' ' * 10 + "You'd better import one module at a time.")
                temp_line = line.strip()
                modules = temp_line[temp_line.index(' ') + 1:]
                modules = modules.strip()
                pattern = re.compile(r'\s*,\s*')
                modules = pattern.split(modules)
                temp_line = ''
                for module in modules:
                    temp_line += line[:line.index('import')] + 'import ' + module + '\n'
                line = temp_line
            pri_line = lines[i - 1].strip()
            if pri_line and (not pri_line.startswith('import')) and \
                    (not pri_line.startswith('#')):
                flag = False
                print(' ' * 10 + 'You should add a blank line before this line.')
                line = '\n' + line
            after_line = lines[i + 1].strip()
            if after_line and (not after_line.startswith('import')):
                flag = False
                print(' ' * 10 + 'You should add a blank line after this line.')
                line = line + '\n'
        # check if there is a blank line before new funtional code block
        # including the class/function definition
        if line.strip() and not line.startswith(' ') and i > 0:
            pri_line = lines[i - 1]
            if pri_line.strip() and pri_line.startswith(' '):
                flag = False
                print(' ' * 10 + "You'd better add a blank line before this line.")
                line = '\n' + line
        if flag:
            print(' ' * 10 + 'Pass.')
        fp.write(line)
    fp.close()


if __name__ == '__main__':
    #fileName = sys.argv[1]  # 命令行参数
    fileName='Car.py'
    fileLines = []
    with open(fileName, 'r') as fp:
        fileLines = fp.readlines()
    desFileName = fileName[:-3] + '_new.py'
    checkFormats(fileLines, desFileName)
    # check the ratio of comment lines to all lines
    comments = [line for line in fileLines if line.strip().startswith('#')]
    ratio = len(comments) / len(fileLines)
    if ratio <= 0.3:
        print('=' * 30)
        print('Comments in the file is less than 30%.')
        print('Perhaps you should add some comments at appropriate position.')

源码链接:
https://download.csdn.net/download/qxyloveyy/12184578
Car类(解析文件)链接:https://download.csdn.net/download/qxyloveyy/12184562

3.在2的基础上实现对打开文件的各种属性的解析,功能如下:
a.实现读取源代码(一个.py文件)
b.实现对代码的遍历解析(主要功能)
c.返回代码的详细信息,例如输出文件名,输出类(class)、方法(function)以及其他信息

import re
import os
import sys

classes = {}	记录class信息
functions = []
variables = {'normal': {}, 'parameter': {}, 'infor': {}}

'''This is a test string:
atest, btest = 3, 5
to verify that variables in comments will be ignored by this algorithm
'''


def _identifyClassNames(index, line):		#实现对类信息的解析
    '''parameter index is the line number of line,
     parameter line is a line of code of the file to check'''
    pattern = re.compile(r'(?<=class\s)\w+(?=.*?:)')	#正则表达式
    matchResult = pattern.search(line)
    if not matchResult:
        return
    className = matchResult.group(0)	
    classes[className] = classes.get(className, [])
    classes[className].append(index)


def _identifyFunctionNames(index, line):	#解析方法,即函数
    pattern = re.compile(r'(?<=def\s)(\w+)\((.*?)\)(?=:)')
    matchResult = pattern.search(line)
    if not matchResult:
        return
    functionName = matchResult.group(1)
    functions.append((functionName, index))
    parameters = matchResult.group(2).split(r', ')
    if parameters[0] == '':
        return
    for v in parameters:
        variables['parameter'][v] = variables['parameter'].get(v, [])
        variables['parameter'][v].append(index)


def _identifyVariableNames(index, line):	#解析其他字符,例如if '__name__'=='__main__':
    # find normal variables, including the case: a, b = 3, 5
    pattern = re.compile(r'\b(.*?)(?=\s=)')
    matchResult = pattern.search(line)
    if matchResult:
        vs = matchResult.group(1).split(r', ')
        for v in vs:
            # consider the case 'if variable == value'
            if 'if ' in v:
                v = v.split()[1]
            # consider the case: 'a[3] = 3'
            if '[' in v:
                v = v[0:v.index('[')]
            variables['normal'][v] = variables['normal'].get(v, [])
            variables['normal'][v].append(index)
    # find the variables in for statements
    pattern = re.compile(r'(?<=for\s)(.*?)(?=\sin)')
    matchResult = pattern.search(line)
    if matchResult:
        vs = matchResult.group(1).split(r', ')
        for v in vs:
            variables['infor'][v] = variables['infor'].get(v, [])
            variables['infor'][v].append(index)


def output():	#输出格式
    print('=' * 30)
    print('The class names and their line numbers are:')
    for key, value in classes.items():
        print(key, ':', value)
    print('=' * 30)
    print('The function names and their line numbers are:')
    for i in functions:
        print(i[0], ':', i[1])
    print('=' * 30)
    print('The normal variable names and their line numbers are:')
    for key, value in variables['normal'].items():
        print(key, ':', value)
    print('-' * 20)
    print('The parameter names and their line numbers in functions are:')
    for key, value in variables['parameter'].items():
        print(key, ':', value)
    print('-' * 20)
    print('The variable names and their line numbers in for statements are:')
    for key, value in variables['infor'].items():
        print(key, ':', value)


# suppose the lines of comments less than 50
def comments(index):	#通过索引来记录字符串行数
    for i in range(50):
        line = allLines[index + i].strip()
        if line.endswith('"""') or line.endswith("'''"):
            return i + 1


if __name__ == '__main__':
    #fileName = sys.argv[1]  # 命令行参数
    fileName='Car.py'
    if not os.path.isfile(fileName):
        print('Your input is not a file.')
        sys.exit(0)  # 退出当前程序
    if not fileName.endswith('.py'):
        print('Sorry. I can only check Python source file.')	#文件格式必须为python源文件
        sys.exit(0)
    allLines = []
    with open(fileName, 'r') as fp:
        allLines = fp.readlines()
    index = 0
    totalLen = len(allLines)
    while index < totalLen:
        line = allLines[index]
        # strip the blank characters at both end of line
        line = line.strip()
        # ignore the comments starting with '#'
        if line.startswith('#'):
            index += 1
            continue
        # ignore the comments between ''' or """
        if line.startswith('"""') or line.startswith("'''"):
            index += comments(index)
            continue
        # identify identifiers
        _identifyClassNames(index + 1, line)
        _identifyFunctionNames(index + 1, line)
        _identifyVariableNames(index + 1, line)
        index += 1
    output()

源码链接:
https://download.csdn.net/download/qxyloveyy/12184582

4.在2,3的基础上实现下列功能:
a.生成新的文件
b.生成文件包含的内容全部是随机内容,包括名字,年龄,性别,简介,email等信息

# coding=utf-8
import random
import string
import codecs

# 常用汉字Unicode编码表
StringBase = '\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6'
StringBase = ''.join(StringBase.split('\\u'))  # 转换为汉字


def getEmail():	#生成随机的email字符串
    suffix = ['.com', '.org', '.net', '.cn']  # 常见域名后缀,可以随意扩展该列表
    characters = string.ascii_letters + string.digits + '_'
    username = ''.join((random.choice(characters) for i in range(random.randint(6, 12))))
    domain = ''.join((random.choice(characters) for i in range(random.randint(3, 6))))
    return username + '@' + domain + random.choice(suffix)


def getTelNo():	#随生成号码
    return ''.join((str(random.randint(0, 9)) for i in range(11)))


def getNameOrAddress(flag):	
    '''flag=1表示返回随机姓名,flag=0表示返回随机地址'''
    result = ''
    if flag == 1:
        rangestart, rangeend = 2, 5  # 大部分中国人姓名在2-4个汉字
    elif flag == 0:
        rangestart, rangeend = 10, 30  # 假设地址在10-30个汉字之间
    else:
        print('flag must be 1 or 0')
        return ''
    for i in range(random.randint(rangestart, rangeend)):
        result += random.choice(StringBase)
    return result


def getSex():
    return random.choice(('男', '女'))


def getAge():
    return str(random.randint(18, 100))


def main(filename):	#将获得的字符串打包为一个整体
    with codecs.open(filename, 'w', 'utf-8') as fp:
        fp.write('Name,Sex,Age,TelNO,Address,Email\n')
        # quickly generate information of 2000 persons
        for i in range(20):
            name = getNameOrAddress(1)
            sex = getSex()
            age = getAge()
            tel = getTelNo()
            address = getNameOrAddress(0)
            email = getEmail()
            line = name + ',' + sex + ',' + age + ',' + tel + ',' + address + ',' + email + '\n'
            fp.write(line)


def output(filename):	#输出到对话框查看信息(检验是否生成随机信息,按行输出,以,结尾)
    with codecs.open(filename, 'r', 'utf-8') as fp:
        while True:
            line = fp.readline()
            if not line:
                return
            line = line.split(',')
            for i in line:
                print(i, end=',')
            print()


if __name__ == '__main__':
    filename = 'information.txt'
    main(filename)
    output(filename)

源码链接:
https://download.csdn.net/download/qxyloveyy/12184336

Python字符串详解参看文章:
https://blog.csdn.net/qxyloveyy/article/details/104449051

谢谢观看!

你可能感兴趣的:(Algorithmic,strategies,字符串,python,正则表达式,random)