包、模块、集合练习题

模块引用的四种方法:
1 相同目录
2 sys.path.append来添加
3 环境变量的pythonpath指定路径,必须重启cmd
4 在python安装路径下的site-packages的目录下添加

习题1:
写一个包,里面实现一个模块,模块里面有个类,有两个实例方法,一个方法可以统计一个路径文件的英文个数,一个是统计空白字符个数。
再实现一下调用类的逻辑

思路:新建一个目录:count
下面新建一个文件__init__.py
sting_count.py

class Count(object):
  
    def __init__(self,file_path):
        self.file_path = file_path

    def count_letter_num(self):
        letter_num = 0
        try:
            with open(self.file_path) as fp:
                for line in fp:
                    for letter in line:
                        if (letter >="a" and letter <="z") or \
                        (letter >="A" and letter <="Z"):
                            letter_num+=1
            return letter_num
        except IOError as e:
            print(e)
            return None

    def count_space_num(self):
        space_num = 0
        try:
            with open(self.file_path) as fp:
                for line in fp:
                    for letter in line:
                        if letter.isspace():
                            space_num+=1
            return space_num
        except IOError as e:
            print(e)
            return None

在这里插入图片描述
在这里插入图片描述
调用包的程序:

import count.string_count

f = count.string_count.Count("f:\\b.py")
print(f.count_letter_num())
print(f.count_space_num())

在这里插入图片描述
在这里插入图片描述

习题2:
统计一下两个句子中不重复单词数量,并列出哪些单词出现了重复值。

import string
s1 = "I am a boy,good boy!"
s2 = "I am not a boy,good girl!"

for i in string.punctuation:
    s1 = s1.replace(i," ")
    s2 = s2.replace(i," ")

word_list1 = set(s1.split())
word_list2 = set(s2.split())

#print(len(list(word_list1^word_list2))) 方法1
result1 = word_list1 - word_list2
result2 = word_list2 - word_list1

result = len(list(result1|result2))
print(result)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值