#方法的使用
str.find(x) ——检测str字符串有没有x字符,有返回索引,没有返回-1 (从左侧找)
str.rfind(x) ——检测str字符串有没有x字符,有返回索引,没有返回-1 (从右侧找)
s.index(x) ——第一次出现该元素的位置,没找到会报错(从左侧找)
s.rindex(x) ——第一次出现该元素的位置,没找到会报错(从右侧找)
s.count(x) ——该元素出现的总次数
str.split(sep=None) ——返回一个列表,由str根据sep被分隔的部分组成(从左侧找)
str.rsplit() ——返回一个列表,由str根据sep被分隔的部分组成(从右侧找)
partition()——将字符串以某个子串分割成三段,返回一个包含三段字符串的列表(从左侧找)
rparttition——将字符串以某个子串分割成三段,返回一个包含三段字符串的列表(从右侧找)
str.join(iter)——在iter变量除最后元素外每个元素后增加一个str
str.lower()——str全部小写
str.upper()——str全部大写
capitalize()——将字符串的首字母大写
title()——将字符串每个单词的首字母大写
swapcase()——将字符串的大写转小写,小写转大写
str.replace(old, new)——将所有old子串替换为new
maketrans()——返回可用于str.translate()的转换表。 translate()
str.center(width,"fillchar")——根据width宽度居中,两边是fillchar
ljust——指定的字符串宽度和特定字符来调整字符串宽度,原字符串位于新字符串的左端
rjust——指定的字符串宽度和特定字符来调整字符串宽度,原字符串位于新字符串的右端
str.strip(chars)——从str中去除其左侧和右侧chars中列出的字符
rstrip——从str中去除其左侧chars中列出的字符
lstrip——从str中去除其右侧chars中列出的字符
zfill——为字符串定义长度,如不满足,缺少的部分用0填补
startswitch——判断字符串开始是否是某个成员(元素)
endswitch——判断字符串结尾是否是某个成员(元素)
isalnum——可以判断字符串的字符是否全都是「字母」和「数字」
isalpha——可以判断字符串的字符是否全都是「字母」
isdigit——可以判断字符串的字符是否全都是「数字」
isdecimal——检查字符串是否只包含十进制字符(Unicode数字,,全角数字(双字节))
isnumeric——可用于判断字符串是否是数字,数字包括Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
format() ——数字类型转换成字符串
eval() ——字符串转换成数字类型
三、程序设计题
*1.三国演义词频
import jieba
txt = open("path.txt", "r", encoding = "utf-8").read()
excludes = {"将军","却说", "荆州", "二人", "不可", "不能", "如此"}
words = jieba.luct(txt)
counts{}
for word in words:
if len(word) == 1
continue
elif word == "诸葛亮" or word == "孔明曰":
rword = "孔明"
elif word == "关公" or word == "云长":
rword = "关羽"
elif word == "玄德" or word == "玄德曰":
rword = "刘备"
elif word == "孟德" or word == "丞相":
rword = "曹操"
else:
rword = word
counts[rword] = counts.get(rword, 0) + 1
for word in excludes:
del counts[word]
items = list(counts.items())
items.sort(key = lambda x:x[1], reverse = True)
for i in range(10)
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))
import jieba
txt = open("path.txt", "r", encoding = "utf-8").read
words = jieba.luct(txt)
counts = {}
for word in words:
if len(word) == 1
continue
else:
counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
items.sort(key = lambda x:x[1], reverse = True)
for i in range(15):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))
*2.温度转换
TempStr = input("请输入带有符号的温度值:")
if TempStr[-1] in ['F', 'f']:
c = (eval(TemptStr[0:-1]) - 32)/1.8
print("转换后的温度是{:.2f}C".format(C))
elif TempStr[-1] in ['C', 'c']:
c = 1.8*eval(TemptStr[0:-1]) + 32
print("转换后的温度是{:.2f}F".format(F))
else:
print("输入格式有误")
*3.获取星期字符串
weekStr = "星期一星期二星期三星期四星期五星期六星期日"
weekId = eval(input("请输入数字(1-7):"))
pos = (weekId - 1)*3
print(weekStr[pos:pos+3]
4.编写程序,模拟抓狐狸小游戏。假设一共有一排5个洞口,小狐狸最开始的时候在其中一个洞口,然后玩家随机打开一个洞口,如何里面有狐狸就抓到了。如果洞口里没有狐狸就到第二天再来抓,但是第二天狐狸会在玩家来抓之前跳到隔壁洞口里。如果在规定的次数内抓到了狐狸就提前结束游戏并提示成果,如果规定的次数用完还没有抓到狐狸,就结束游戏并提示失败。
import random
class FoxGame:
def __init__(self, num_holes=5, max_attempts=10):
self.num_holes = num_holes
self.max_attempts = max_attempts
self.fox_location = random.randint(1, num_holes)
self.player_attempts = 0
def display_instructions(self):
print("欢迎来到抓狐狸小游戏!")
print("你需要在规定的次数内抓住藏在洞口的狐狸。")
print("每天你可以选择打开一个洞口,看看狐狸在不在那里。")
print("但是,狐狸会在你来抓之前跳到隔壁洞口。")
print(f"有 {self.num_holes} 个洞口,狐狸最开始在其中一个。")
def check_fox_location(self, chosen_hole):
if chosen_hole == self.fox_location:
print("恭喜你,抓住了狐狸!")
return True
else:
print("糟糕,狐狸不在这个洞口。")
return False
def play_game(self):
self.display_instructions()
while self.player_attempts < self.max_attempts:
chosen_hole = int(input(f"\n第 {self.player_attempts + 1} 天,请选择打开哪个洞口(1-{self.num_holes}):"))
if 1 <= chosen_hole <= self.num_holes:
self.fox_location = random.choice(
[hole for hole in range(1, self.num_holes + 1) if hole != chosen_hole]
)
if self.check_fox_location(chosen_hole):
print(f"你在第 {self.player_attempts + 1} 天成功抓到了狐狸!")
break
else:
print(f"狐狸已经跳到了其他洞口。")
self.player_attempts += 1
else:
print("无效的选择,请选择1到洞口的范围内的数字。")
if self.player_attempts == self.max_attempts:
print(f"\n抓狐狸失败,你已经用完了 {self.max_attempts} 次机会。狐狸成功逃脱。")
if __name__ == "__main__":
game = FoxGame()
game.play_game()
5.古代的秤是一斤16两,计算:在控制台中获取两,计算是几斤几两?
number = fload(input("请输入重量(两):"))
jing = int(number//16)
liang = number%16
print(str(number) + "两是" + str(jing) + "斤" + str(liang) + "两")
6.在控制台录入日期(月、日),计算这是一年的第几天。
month = eval(input("请输入月份:"))
day = eval(input("请输入天数:"))
month_day = (31, 28, 31, 30, 31, 30, 31, 31 30, 31, 30, 31)
total_day = 0
for item in month_day[:month-1]:
total_day+=item
total_day+=day
print(total_day)
四、综合设计题
*1.有一个汽车类vehicle,类中的私有数据成员为车轮数wheels和车重weight;小车类car是汽车类vehicle派生类,其中包括载客人数passenger_load,默认为四人;卡车类Truck是汽车类vehicle派生类,其中包括载客人数passenger_load和载重量payload。(提示:vehicle类定义display()显示车轮和重量,car和Trunk中要求对display()进行同名覆盖)
class Vehicle:
def__init__(self, wheels, weight):
self.setWheels(wheels)
self.setWeight(weight)
def setWheels(self.wheels):
self.__wheels = wheels
def setWeight(self.weight):
self.__weight = weight
def getWheels(self):
return self.__wheels
def getWheels(self):
return self.__weight
def display(self):
print("车轮 = {0}, 重量 = {1}".format(self.getWhells(), self.getWeight()))
class Car(Vehicle):
def__init__(self, wheels, weight, passenger_load = 4):
super(car, self).__init__(wheels, weight)
self.setPassenger(passenger_load)
def setPassenger(self, passenger_load):
self._passenger_load = passenger_load
def getPassenger(self):
return self._passenger_load
def display(self):
print("车轮 = {0}, 重量 = {1}, 载客人数 = {2}".format(self.getWheels(),
self.getWeight(), slef.getPassenger())
class Trunk(Vehicle):
def__init__(self, wheels, weight, passenger_load, payload):
super(Trunk, self).__init__(wheels, weight)
self.setPassenger(passenger_load)
self.setPayload(payload)
def setPassenger(self, passenger_load):
self._passenger_load = passenger_load
def setPayload(self, payload):
self._payload = payload
def getPassenger(self):
return self._passenger_load
def getPayload(self):
return self._payload
def display(self):
print("车轮 = {0}, 重量 = {1}, 载客人数 = {2}, 载重量 = {3}".
format(self.getWheels(), self.getWeight(), slef.getPassenger())
vehicle = Vehicle(4, 10000)
vehicle.display()
car = Car(4, 10000, 4)
car.display()
trunk = Trunk(4, 10000, 4, 120)
trunk.display()
*2.定义Animal类, 至少包含一个属性和一个方法,定义Cat类、 Dog类、 Bird类,使这些类继承自Animal类,定义Person类,使人可以通过Animal喂食Cat类、Dog类、Bird类的实例
class Animal(object):
def __init__(self, height, color):
self.height = height
self.color = color
print("身高:%dcm" % (self.height)) # 格式化输出
print("颜色:%s" % (self.color))
def eat(self):
print("吃东西")
class Cat(Animal):
def __init__(self, height, color, name, age):
super().__init__(height, color) # 使用super()调用父类的构造函数
self.name = name
self.age = age
def meow(self):
print("喵喵叫")
class Dog(Animal):
def __init__(self, height, color, name, age):
super().__init__(height, color) # 使用super()调用父类的构造函数
self.name = name
self.age = age
print("名字:%s" % (self.name))
print("年龄:%d岁" % (self.age))
def eat(self):
print("狗吃骨头")
class Bird(Animal):
def __init__(self, height, color, species):
super().__init__(height, color) # 使用super()调用父类的构造函数
self.species = species
def chirp(self):
print("鸟儿唧唧叫")
class Person:
def feed_animal(self, animal):
print(f"喂食 {animal.__class__.__name__}: {animal.height}cm {animal.color}")
animal.eat()
# 实例化类
if __name__ == "__main__":
my_dog = Dog(55, "黑色", "汪汪", 2)
my_cat = Cat(30, "白色", "喵喵", 3)
my_bird = Bird(15, "彩色", "小鸟")
person = Person()
person.feed_animal(my_dog)
person.feed_animal(my_cat)
person.feed_animal(my_bird)
3.编写程序,实现一名为“Rectangle”的表示矩阵的类,该类包含两个实例属性width和height都是可读写的property,分别表示矩阵的宽和高,同时还有一个名为area()的方法,是一个只读的property。该方法返回矩阵的面积。继承上面的的Rectangle类和实现一个名为Square的正方形类。使得可以用square(边长)的方式实例化该类。密码判断:用户密码的格式是:1.以大写或小写字母开头。2.至少要有8个字符,最长不限。3.由数字,字母,下划线或“-”组成。输入若干字符串判断是否符合密码条件,如果是,输出yes,如果不是输出no。
import re
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def area(self):
return self._width * self._height
class Square(Rectangle):
def __init__(self, side_length):
super().__init_ _(side_length, side_length)
def is_valid_password(password):
# 密码的正则表达式匹配规则
pattern = re.compile(r"^[A-Za-z][A-Za-z0-9_-]{7,}$")
return bool(pattern.match(password))
# 测试 Rectangle 类
rectangle = Rectangle(width=5, height=10)
print(f"Rectangle Width: {rectangle.width}")
print(f"Rectangle Height: {rectangle.height}")
print(f"Rectangle Area: {rectangle.area}")
# 测试 Square 类
square = Square(side_length=7)
print(f"Square Side Length: {square.width}")
print(f"Square Area: {square.area}")
# 测试密码判断函数
passwords = ["Abcdefg1", "12345678", "Abc_def-123", "invalidpassword"]
for password in passwords:
result = "yes" if is_valid_password(password) else "no"
print(f"Password: {password} - {result}")