Python全栈工程师

21.2-习题命令分发器、copy和单词统计

2019-10-08  本文已影响0人  BeautifulSoulpy

真正成熟的人,首先应该是一个懂得克制自己欲望的人。
克制,其实是一种更高级的自律。

所谓“美女都是狠角色”,不是没有道理的。

就我身边的大多数美女而言,她们可以克制住自己不胡吃海喝、不沾辛辣、不熬夜,在别人偷懒的时候,她们坚持运动,每天敷面膜、保养皮肤。

“学霸”也不是不食人间烟火,更不是没有七情六欲,他们不过是比常人更懂得克制自己。

我认识的一位学霸,大学那么多年都觉得他除了学习,简直无欲无求。

谁知等他拿到了心仪企业的offer和研究生的录取通知后,一口气做了两件大事:脱单+一个月的长途旅行。

真正成熟的人,知道自己想要的是什么,更知道自己什么时候该做什么事情,懂得克制自己。

在别人都在玩的时候,努力克制。等拥有了足够的选择权之后,再去放肆。

完善命令分发器,实现函数可以带任意参数(可变参数除外),解析参数并要求用户输入
即解决下面的问题;

思路:可以有2种方式

1、注册的时候,固定死,@reg('py',200,100)
可以认为@reg('py',200,100)和@reg('py',300,100)是不同的函数,可以用partial函数。
2、运行时,在输入cmd的时候,逗号或空格分割,获取参数。
至于函数的验证,以后实现。
一般用户都喜欢使用单纯一个命令如mag,然后直接显示想要的结果,所以采用第一种方式

from functools import partial

def command_dispatcher(defaultfn=lambda :print('Unknown command')):
    # 构建全局字典
    cmd_tb1 = {}
    
    #注册函数
    def reg(cmd,*args,**kwargs):
        def _reg(fn):
            func = partial(fn,*args,**kwargs)
            commands[cmd] = func
            return func
        return _reg

    def default_func():
        print("Unknown command")

    def dispatcher():
        while True:
            cmd = input('>>>').strip()
            # 退出条件
            if cmd == '':
                print('bye')
                return
            cmd_tb1.get(cmd, default_func)()
            
    return reg,dispatcher
        
reg, dispatcher = command_dispatcher()
        
@reg('mag',z=200,y=300,x=100)
@reg('mag1',z=300,y=300,x=300)
def foo1(x,y,z):
    print('magedu',x,y,z)
   
@reg('py',300,b=400)
def foo2(a,b=100):
    print('python',a,b)
#reg('mag', foo1)
#reg('py', foo2)

dispatcher()

练习1: copy文件内容

复制tmp目录下文件1里面的内容到一个新文本中;

filename1 = './tmp/test.txt'
filename2 = './tmp/test1.txt'

f = open(filename1,'w+')
lines = ['abc','123','magedu']
f.writelines('\n'.join(lines))

f.seek(0)
print(f.read())
f.close()

def copy(src,dest):
    with open(src) as f1:
        with open(dest,'w') as f2:
            f2.write(f1.read())
            
copy(filename1,filename2)
----------------------------------------------------------------
abc
123
magedu

总结:
1.只要是文件操作,能用 with 就用 with ;看见open,就想一想要不要用with;

练习2: 单词统计

# 缺省字典
from collections import defaultdict
filename = './sample.txt'
count = 0
d = defaultdict(lambda:0)   # 缺省字典判断
with open(filename,encoding='utf8') as f:
    for line in f:
        print(line)
        count += 1
        #if count == 5:break
            
        words = line.split()
        for word in words:
            d[word] += 1
            
print(sorted(d.items(),key=lambda x: x[1],reverse=True))
----------------------------------------------------------------------------------
[('the', 124), ('is', 60), ('a', 54), ('path', 52), ('and', 39), ('of', 33), ('if', 32), ('to', 31), ('or', 24), ('Return', 22), ('in', 20), ('an', 18), ('on', 17), ('file', 17), ('for', 16), ('pathname', 15), ('not', 15), ('On', 15), ('be', 14), ('that', 14), ('path.', 14), ('drive', 14), ('are', 13), ('by', 13), ('True', 13), ('The', 12), ('as', 12), ('same', 12), ('all', 11), ('will', 11), ('Windows', 10), ('This', 10), ('returns', 10), ('If', 10), ('it', 10), ('Python', 9), ('version', 9), ('function', 9), ('directory', 9), ('»', 8), ('Unix,', 8), ('paths', 8), ('return', 8), ('symbolic', 8), ('Windows,', 8), ('number', 8), ('can', 7), ('different', 7), ('this', 7), ('from', 7), ('with', 7), ('time', 7), ('|', 6), ('module', 6), ('names', 6), ('may', 6), ('does', 6), ('empty', 6), ('Raise', 6), ('contains', 6), ('Availability:', 6), ('path,', 6), ('component', 6), ('last', 6), ('point', 6), ('mount', 6), ('Windows.', 6), ('see', 5), ('either', 5), ('so', 5), ('Unix', 5), ('use', 5), ('string', 5), ('Note', 5), ('result', 5), ('name', 5), ('always', 5), ('pair', 5), ('returned', 5), ('both', 5), ('absolute', 5), ('empty.', 5), ('Changed', 5), ('directory.', 5), ('up', 5), ('value', 5), ('since', 5), ('into', 5), ('tail', 5), ('previous', 4), ('some', 4), ('objects', 4), ('any', 4), ('also', 4), ('one', 4), ('where', 4), ('relative', 4), ('existing', 4), ('False', 4), ('initial', 4), ('current', 4), ('OSError', 4), ('exist', 4), ('inaccessible.', 4), ('slashes', 4), ('Split', 4), ('head', 4), ('modules', 3), ('(for', 3), ('functions', 3), ('To', 3), ('represent', 3), ('strings', 3), ('should', 3), ('bytes', 3), ('only', 3), ('operating', 3), ('systems', 3), ('have', 3), ('there', 3), ('system', 3), ('basename', 3), ('each', 3), ('refers', 3), ('links.', 3), ('~user', 3), ('replaced', 3), ('environment', 3), ('variable', 3), ('used', 3), ('supported', 3), ('giving', 3), ('seconds', 3), ('epoch', 3), ('(see', 3), ('module).', 3), ('begins', 3), ('file.', 3), ('device', 3), ('letter', 3), ('root', 3), ('UNC', 3), ('3.4:', 3), ('components', 3), ('part', 3), ('converts', 3), ('refer', 3), ('Added', 3), ('support.', 3), ('tail)', 3), ('contain', 3), ('string.', 3), ('Navigation', 2), ('index', 2), ('next', 2), ('3.5.3', 2), ('Documentation', 2), ('Standard', 2), ('Library', 2), ('11.', 2), ('File', 2), ('Directory', 2), ('Access', 2), ('os.path', 2), ('—', 2), ('implements', 2), ('filesystem', 2), ('bytes.', 2), ('character', 2), ('applications', 2), ('arbitrary', 2), ('using', 2), ('standard', 2), ('access', 2), ('Unlike', 2), ('do', 2), ('such', 2), ('when', 2), ('paths.', 2), ('you', 2), ('most', 2), ('platforms,', 2), ('element', 2), ('passing', 2), ('split().', 2), ("('').", 2), ('longest', 2), ('valid', 2), ('New', 2), ('prefix', 2), ('empty,', 2), ('at', 2), ('>>>', 2), ("'/usr/local/lib'])", 2), ('open', 2), ('Returns', 2), ('broken', 2), ('os.stat()', 2), ('now', 2), ('argument', 2), ('~', 2), ('home', 2), ('HOME', 2), ('otherwise', 2), ('looked', 2), ('password', 2), ('An', 2), ('unchanged.', 2), ('variables', 2), ('$name', 2), ('references', 2), ('os.stat_float_times()', 2), ('True,', 2), ('floating', 2), ('number.', 2), ('(like', 2), ('pathname.', 2), ('slash,', 2), ('follows', 2), ('links,', 2), ('islink()', 2), ('true', 2), ('links', 2), ('been', 2), ('whether', 2), ('i-node', 2), ('points', 2), ('other', 2), ('more', 2), ('separator', 2), ('meaning', 2), ('thrown', 2), ('away', 2), ('letter,', 2), ('Normalize', 2), ('forward', 2), ('backward', 2), ('slashes.', 2), ('system).', 2), ('start', 2), ('3.2:', 2), ('everything', 2), ('In', 2), ('cases,', 2), ('+', 2), ('including', 2), ('e.g.', 2), ('"/dir")', 2), ('ext', 2), ('unc', 2), ('(such', 2), ('rest', 2), ('Software', 2), ('11.2.', 1), ('Common', 1), ('manipulations', 1), ('Source', 1), ('code:', 1), ('Lib/posixpath.py', 1), ('POSIX),', 1), ('Lib/ntpath.py', 1), ('NT),', 1), ('Lib/macpath.py', 1), ('Macintosh)', 1), ('--------------------------------------------------------------------------------', 1), ('useful', 1), ('pathnames.', 1), ('read', 1), ('write', 1), ('files', 1), ('open(),', 1), ('accessing', 1), ('os', 1), ('module.', 1), ('parameters', 1), ('passed', 1), ('strings,', 1), ('Applications', 1), ('encouraged', 1), ('(Unicode)', 1), ('strings.', 1), ('Unfortunately,', 1), ('representable', 1), ('need', 1), ('support', 1), ('names.', 1), ('Vice', 1), ('versa,', 1), ('cannot', 1), ('(in', 1), ('mbcs', 1), ('encoding),', 1), ('hence', 1), ('files.', 1), ('unix', 1), ('shell,', 1), ('automatic', 1), ('expansions.', 1), ('Functions', 1), ('expanduser()', 1), ('expandvars()', 1), ('invoked', 1), ('explicitly', 1), ('application', 1), ('desires', 1), ('shell-like', 1), ('expansion.', 1), ('(See', 1), ('glob', 1), ('module.)', 1), ('See', 1), ('pathlib', 1), ('offers', 1), ('high-level', 1), ('objects.', 1), ('All', 1), ('these', 1), ('accept', 1), ('their', 1), ('parameters.', 1), ('object', 1), ('type,', 1), ('returned.', 1), ('Since', 1), ('conventions,', 1), ('several', 1), ('versions', 1), ('library.', 1), ('suitable', 1), ('running', 1), ('on,', 1), ('therefore', 1), ('usable', 1), ('local', 1), ('However,', 1), ('import', 1), ('individual', 1), ('want', 1), ('manipulate', 1), ('formats.', 1), ('They', 1), ('interface:', 1), ('posixpath', 1), ('UNIX-style', 1), ('ntpath', 1), ('macpath', 1), ('old-style', 1), ('MacOS', 1), ('os.path.abspath(path)', 1), ('normalized', 1), ('absolutized', 1), ('equivalent', 1), ('calling', 1), ('normpath()', 1), ('follows:', 1), ('normpath(join(os.getcwd(),', 1), ('path)).', 1), ('os.path.basename(path)', 1), ('base', 1), ('second', 1), ('program;', 1), ("'/foo/bar/'", 1), ("'bar',", 1), ('basename()', 1), ('os.path.commonpath(paths)', 1), ('common', 1), ('sub-path', 1), ('sequence', 1), ('ValueError', 1), ('pathnames,', 1), ('commonprefix(),', 1), ('3.5.', 1), ('os.path.commonprefix(list)', 1), ('(taken', 1), ('character-by-character)', 1), ('list.', 1), ('list', 1), ('invalid', 1), ('because', 1), ('works', 1), ('time.', 1), ('obtain', 1), ('commonpath().', 1), ("os.path.commonprefix(['/usr/lib',", 1), ("'/usr/l'", 1), ("os.path.commonpath(['/usr/lib',", 1), ("'/usr'", 1), ('os.path.dirname(path)', 1), ('first', 1), ('os.path.exists(path)', 1), ('descriptor.', 1), ('permission', 1), ('granted', 1), ('execute', 1), ('requested', 1), ('file,', 1), ('even', 1), ('physically', 1), ('exists.', 1), ('3.3:', 1), ('integer:', 1), ('descriptor,', 1), ('otherwise.', 1), ('os.path.lexists(path)', 1), ('Equivalent', 1), ('exists()', 1), ('platforms', 1), ('lacking', 1), ('os.lstat().', 1), ('os.path.expanduser(path)', 1), ('user‘s', 1), ('set;', 1), ('user’s', 1), ('through', 1), ('built-in', 1), ('pwd.', 1), ('directly', 1), ('USERPROFILE', 1), ('set,', 1), ('combination', 1), ('HOMEPATH', 1), ('HOMEDRIVE', 1), ('used.', 1), ('handled', 1), ('stripping', 1), ('created', 1), ('user', 1), ('derived', 1), ('above.', 1), ('expansion', 1), ('fails', 1), ('begin', 1), ('tilde,', 1), ('os.path.expandvars(path)', 1), ('expanded.', 1), ('Substrings', 1), ('form', 1), ('${name}', 1), ('name.', 1), ('Malformed', 1), ('non-existing', 1), ('left', 1), ('%name%', 1), ('expansions', 1), ('addition', 1), ('${name}.', 1), ('os.path.getatime(path)', 1), ('os.path.getmtime(path)', 1), ('modification', 1), ('os.path.getctime(path)', 1), ('system’s', 1), ('ctime', 1), ('which,', 1), ('Unix)', 1), ('metadata', 1), ('change,', 1), ('and,', 1), ('others', 1), ('Windows),', 1), ('creation', 1), ('os.path.getsize(path)', 1), ('size,', 1), ('bytes,', 1), ('os.path.isabs(path)', 1), ('means', 1), ('(back)slash', 1), ('after', 1), ('chopping', 1), ('off', 1), ('potential', 1), ('letter.', 1), ('os.path.isfile(path)', 1), ('regular', 1), ('isfile()', 1), ('os.path.isdir(path)', 1), ('isdir()', 1), ('os.path.islink(path)', 1), ('entry', 1), ('link.', 1), ('Always', 1), ('runtime.', 1), ('os.path.ismount(path)', 1), ('point:', 1), ('has', 1), ('mounted.', 1), ('POSIX,', 1), ('checks', 1), ('path‘s', 1), ('parent,', 1), ('path/..,', 1), ('than', 1), ('path/..', 1), ('detect', 1), ('POSIX', 1), ('variants.', 1), ('share', 1), ('points,', 1), ('GetVolumePathName', 1), ('called', 1), ('input', 1), ('Support', 1), ('detecting', 1), ('non-root', 1), ('os.path.join(path,', 1), ('*paths)', 1), ('Join', 1), ('intelligently.', 1), ('concatenation', 1), ('members', 1), ('*paths', 1), ('exactly', 1), ('(os.sep)', 1), ('following', 1), ('non-empty', 1), ('except', 1), ('last,', 1), ('end', 1), ('joining', 1), ('continues', 1), ('component.', 1), ('reset', 1), ('(e.g.,', 1), ("r'\\foo')", 1), ('encountered.', 1), ('reset.', 1), ('drive,', 1), ('os.path.join("c:",', 1), ('"foo")', 1), ('represents', 1), ('C:', 1), ('(c:foo),', 1), ('c:\\foo.', 1), ('os.path.normcase(path)', 1), ('case', 1), ('Mac', 1), ('OS', 1), ('X,', 1), ('unchanged;', 1), ('case-insensitive', 1), ('filesystems,', 1), ('lowercase.', 1), ('TypeError', 1), ('type', 1), ('str', 1), ('os.path.normpath(path)', 1), ('collapsing', 1), ('redundant', 1), ('separators', 1), ('up-level', 1), ('A//B,', 1), ('A/B/,', 1), ('A/./B', 1), ('A/foo/../B', 1), ('become', 1), ('A/B.', 1), ('manipulation', 1), ('change', 1), ('normalize', 1), ('case,', 1), ('normcase().', 1), ('os.path.realpath(path)', 1), ('canonical', 1), ('specified', 1), ('filename,', 1), ('eliminating', 1), ('encountered', 1), ('(if', 1), ('they', 1), ('os.path.relpath(path,', 1), ('start=os.curdir)', 1), ('filepath', 1), ('optional', 1), ('computation:', 1), ('accessed', 1), ('confirm', 1), ('existence', 1), ('nature', 1), ('start.', 1), ('defaults', 1), ('os.curdir.', 1), ('os.path.samefile(path1,', 1), ('path2)', 1), ('arguments', 1), ('determined', 1), ('raises', 1), ('exception', 1), ('call', 1), ('fails.', 1), ('uses', 1), ('implementation', 1), ('platforms.', 1), ('os.path.sameopenfile(fp1,', 1), ('fp2)', 1), ('descriptors', 1), ('fp1', 1), ('fp2', 1), ('os.path.samestat(stat1,', 1), ('stat2)', 1), ('stat', 1), ('tuples', 1), ('stat1', 1), ('stat2', 1), ('These', 1), ('structures', 1), ('os.fstat(),', 1), ('os.lstat(),', 1), ('os.stat().', 1), ('underlying', 1), ('comparison', 1), ('samefile()', 1), ('sameopenfile().', 1), ('os.path.split(path)', 1), ('pair,', 1), ('(head,', 1), ('leading', 1), ('that.', 1), ('never', 1), ('slash;', 1), ('ends', 1), ('no', 1), ('slash', 1), ('Trailing', 1), ('stripped', 1), ('unless', 1), ('(one', 1), ('only).', 1), ('join(head,', 1), ('location', 1), ('(but', 1), ('differ).', 1), ('Also', 1), ('dirname()', 1), ('basename().', 1), ('os.path.splitdrive(path)', 1), ('(drive,', 1), ('which', 1), ('specifications,', 1), ('splits', 1), ('drive/UNC', 1), ('sharepoint', 1), ('colon.', 1), ('splitdrive("c:/dir")', 1), ('("c:",', 1), ('host', 1), ('share,', 1), ('but', 1), ('fourth', 1), ('separator.', 1), ('splitdrive("//host/computer/dir")', 1), ('("//host/computer",', 1), ('os.path.splitext(path)', 1), ('(root,', 1), ('ext)', 1), ('==', 1), ('period', 1), ('period.', 1), ('Leading', 1), ('periods', 1), ('ignored;', 1), ("splitext('.cshrc')", 1), ("('.cshrc',", 1), ("'').", 1), ('os.path.splitunc(path)', 1), ('Deprecated', 1), ('3.1:', 1), ('Use', 1), ('splitdrive', 1), ('instead.', 1), ('(unc,', 1), ('rest)', 1), ("r'\\\\host\\mount'),", 1), ('present,', 1), ("r'\\path\\file.ext').", 1), ('For', 1), ('containing', 1), ('letters,', 1), ('os.path.supports_unicode_filenames', 1), ('Unicode', 1), ('(within', 1), ('limitations', 1), ('imposed', 1), ('©', 1), ('Copyright', 1), ('2001-2017,', 1), ('Foundation.', 1), ('Foundation', 1), ('non-profit', 1), ('corporation.', 1), ('Please', 1), ('donate.', 1), ('Last', 1), ('updated', 1), ('Jan', 1), ('16,', 1), ('2017.', 1), ('Found', 1), ('bug?', 1), ('Created', 1), ('Sphinx', 1), ('1.3.1.', 1)]

for k in d:
    if k.find('path') > -1:    # 查找不到返回 -1 ,
        print(k)
------------------------------------------------------------
os.path
pathname
Lib/posixpath.py
Lib/ntpath.py
Lib/macpath.py
pathnames.
path
pathlib
paths.
posixpath
paths
ntpath
macpath
os.path.abspath(path)
path.
normpath()
normpath(join(os.getcwd(),
path)).
os.path.basename(path)
os.path.commonpath(paths)
sub-path
...............


# 完整代码;
def makekey(s:str):
    chars = set(r"""!'"#./\()[],*-""")
    key = s.lower()
    ret = []
    for i, c in enumerate(key):
        if c in chars:
            ret.append(' ')
        else:
            ret.append(c)
    return ''.join(ret).split()

def makekey1(s:str):
    chars = set(r"""!'"#./\()[],*-""")

    key = s.lower()
    ret = []
    start = 0
    for i, c in enumerate(key):
        if c in chars:
            if start == i: # 如果紧挨着还是特殊字符,start一定等于i
                start += 1 # 加1并continue
                continue
            ret.append(key[start:i])
            start = i + 1 # 加1是跳过这个不需要的特殊字符c
    else:
        if start < len(key): # 小于,说明还有有效的字符,而且一直到末尾
            ret.append(key[start:])
            
    return ret

print(makekey('a.b.c'))
print(makekey1('[[[[os.path....join(path,)]]]]'))
#-----------------------------------------------------------------------
['a', 'b', 'c']
['os', 'path', 'join', 'path']


d = {}
with open('./sample.txt', encoding='utf8') as f:
    for line in f:
        words = line.split()
        for wordlist in map(makekey1,words):
            for word in wordlist:
                d[word] = d.get(word,0) + 1

for k,v in sorted(d.items(),key=lambda item: item[1],reverse= True):
    print(k,v)
#--------------------------------------------------
path 138
the 136
is 60
a 59
os 49
if 43
and 40
to 34
on 33
of 33
return 30
windows 25
file 24
or 24
in 24
for 20
an 20
pathname 17
this 17
true 17
drive 17
directory 16
unix 16
not 15
that 15
be 14
by 14
empty 14
3 13
are 13
paths 13


上一篇 下一篇

猜你喜欢

热点阅读