从零开始的python之旅(day5)

从零开始的python之旅(day5)

  今天主要学的还是,文件的处理以及字典的运用

  addressBook

from email.quoprimime import decode

def main():
    file2 = open('EmailAddressBook.txt','r',encoding='gbk')
    file1 = open('TeleAddressBook.txt','r',encoding='gbk')
    file1.readline()
    file2.readline()
    file1_list = file1.readlines()
    file2_list = file2.readlines()
    dic1 = {}
    dic2 = {}
    for i in file1_list:
        el = i.split()
        dic1[el[0]] = el[1]
    for i in file2_list:
        el = i.split()
        dic2[el[0]] = el[1]
    list3 = []
    list3.append('姓名\t    电话   \t  邮箱\n')
    for key in dic1.keys():
        s = ''
        if key in dic2.keys():
            s = '\t'.join([key,dic1[key],dic2[key]])
        else :
            s = '\t'.join([key,dic1[key],str('   -----   ')])
        s += '\n'
        list3.append(s)
    for key in dic2.keys():
        s = ''
        if key not in dic1.keys():
            s = '\t'.join([key,str('   -----   '),dic2[key]])
            s += '\n'
        list3.append(s)

    file3 = open('AddressBook.txt','w',encoding='UTF-8')
    file3.writelines(list3)


if __name__ == '__main__':
    main()

  中文编码一般为gbk或者utf-8,在使用时注意具体是什么

  calHamlet

def getText():
    txt = open('hamlet.txt','r').read()
    txt = txt.lower()
    for ch in txt:
        if ch in '~@#$%^&*()_+=<>?/.,;:{}[]|\"""':
            txt = txt.replace(ch, " ")
    return txt
def main():
    hamletTxt = getText()
    words = hamletTxt.split()
    counts = {}
    excludes = {'the','a','to','you','i','and','my','in','of','it'}
    for word in words:
        counts[word] = counts.get(word,0) + 1
    list1 = list(counts.items())
    list1.sort(key = lambda x:x[1],reverse=True)
    count = 0
    for i in list1:
        word,counts = i
        if word in excludes:
            continue
        count += 1
        if(count > 10) :break
        print('{}  {}'.format(word,counts))

if __name__ == '__main__':
    main()

  统计频率,昨天出现过,没啥好说的和昨天差不多,差不多学完了,后面编程内容都和我需要的关系不大,所以我准备提前结束第一周学习内容,然后开始找项目跟进一下代码,有好项目我会分享出来的

posted @ 2025-01-16 21:32  Liyukio  阅读(8)  评论(0)    收藏  举报