day3

1、写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成批量修改操作

代码:
def change_file(file_name,old_word,new_word):
    import os
    with open(file_name, 'r', encoding='utf-8') as read_f, \
            open('temp.swap', 'w', encoding='utf-8') as write_f:
        for data in read_f:
            new_file=data.replace(old_word,new_word)
            new_file2=write_f.write(new_file)
    os.remove(file_name)
    os.rename('temp.swap',file_name)
def input_flie():
    while True:
        user_input=input('please enter file : ').strip()
        if not user_input:continue
        else:
            return user_input
def input_old_word():
    while True:
        old_word_input=input('please enter old word : ').strip()
        if not old_word_input:continue
        else:
            return old_word_input
def input_new_word():
    while True:
        new_word_input=input('please enter new word : ').strip()
        if not new_word_input:continue
        else:
            return new_word_input
def main():
    file=input_flie()
    old=input_old_word()
    new=input_new_word()
    change_file(file,old,new)
    with open(file,mode='r',encoding='utf8') as file_word:
        data=file_word.read()
        print('修改后内容:')
        print(data)
main()

测试结果:
C:\Python36\python.exe D:/OwnCloud/Python/day3/test.py
please enter file : data
please enter old word : dai
please enter new word : alex
修改后内容:
alex say i have on tesla
my name is alex
alex is good
alex xxxx hahaha alex

Process finished with exit code 0

2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

代码:(exit,退出)
def user_input():
    user_input=input('Please Enter String:')
    if user_input=='exit':
        return False
    else:
        return user_input
def compare(user_input):
    length=len(user_input)
    return length
def main():
    tag=True
    while tag:
        inp=user_input()
        if not inp:
            break
        length=compare(inp)
        print(length)
main()

测试结果:
Please Enter String:sdasdasdasdasda sdas d dasd as
30
Please Enter String:!@#!@#%$#56
11
Please Enter String:exit

Process finished with exit code 0

3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5.

代码:
def user_input():
    user_input=input('Please Enter String.List.Tuple: ')
    if user_input=='exit':
        return False
    else:
        return user_input
def compare(user_input):
    if user_input.startswith('(') and \
        user_input.endswith(')'):
        inp_1=tuple(eval(user_input))
        return inp_1
    elif user_input.startswith('[') and \
        user_input.endswith(']'):
        inp_2=list(eval(user_input))
        return inp_2
    else:
        return user_input
def main():
    tag=True
    while tag:
        inp=user_input()
        if not inp:
            break
        length=compare(inp)
        print(length,type(length),len(length))
        if len(length) > 5:
            print("长度大于5")
        elif len(length) == 5:
            print("长度等于5")
        else:
            print("长度小于5")
main()

测试结果:
Please Enter String.List.Tuple: [1,2,3,4,5]
[1, 2, 3, 4, 5] <class 'list'> 5
长度等于5

Please Enter String.List.Tuple: hello !
hello ! <class 'str'> 7
长度大于5

Please Enter String.List.Tuple: ('Michael', 'Bob', 'Tracy')
('Michael', 'Bob', 'Tracy') <class 'tuple'> 3
长度小于5

Please Enter String.List.Tuple: exit

Process finished with exit code 0

4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

代码:
def user_input():
    user_input=input('Please Enter List: ')
    if user_input=='exit':
        return False
    else:
        return user_input
def compare(user_input):
    if user_input.startswith('[') and \
        user_input.endswith(']'):
        user_input=list(eval(user_input))
        return user_input
    else:
        print("(please enter list !)")
        return False
def main():
    tag=True
    while tag:
        inp=user_input()
        if not inp:
            break
        length=compare(inp)
        if not length:
            continue
        print(length,type(length),len(length))
        if len(length) >= 2:
            print(length[0],length[1])
main()

测试结果:
C:\Python36\python.exe D:/OwnCloud/Python/day3/test.py
Please Enter List: 123
(please enter list !)
Please Enter List: [1,2,3,4]
[1, 2, 3, 4] <class 'list'> 4
1 2
Please Enter List: exit

Process finished with exit code 0

5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

代码:
def user_input():
    user_input=input('Please Enter List.Tuple: ')
    if user_input=='exit':
        return False
    else:
        return user_input
def compare(user_input):
    if user_input.startswith('(') and \
        user_input.endswith(')'):
        inp_1=tuple(eval(user_input))
        return inp_1
    elif user_input.startswith('[') and \
        user_input.endswith(']'):
        inp_2=list(eval(user_input))
        return inp_2
    else:
        print("(please enter list.tuple !)")
        return False
def main():
    tag=True
    while tag:
        inp=user_input()
        if not inp:
            break
        length=compare(inp)
        if not length:continue
        new_list=length[::2]
        print(new_list)
main()

测试结果:
C:\Python36\python.exe D:/OwnCloud/Python/day3/test.py
Please Enter List.Tuple: [1,2,3,4,5,6,7]
[1, 3, 5, 7]
Please Enter List.Tuple: ('physics', 'chemistry', 1997, 2000)
('physics', 1997)
Please Enter List.Tuple: exit

Process finished with exit code 0

6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
PS:字典中的value只能是字符串或列表

代码:
dic={"k1":"v1v1","k2":[11,22,33,44]}
def user_input():
    user_input=input("please enter 'dic': ")
    if user_input=='dic':
        return user_input
    else:
        print("(please enter 'dic' )")
        return False
def compare(user_input):
    new_list=[]
    for i in dic:
        if len(dic[i]) >=2:
            new_list.append(dic[i][0])
            new_list.append(dic[i][1])
    return new_list
def main():
    while True:
        inp=user_input()
        if not inp:continue
        res=compare(inp)
        print(res)
main()

测试结果:
C:\Python36\python.exe D:/OwnCloud/Python/day3/test.py
please enter 'dic': dd
(please enter 'dic' )
please enter 'dic': dic
['v', '1', 11, 22]
please enter 'dic': 
posted @ 2017-09-22 23:37  戴成旭  阅读(47)  评论(0)    收藏  举报