python新手入门程序——实验6

1、统计《三国演义》中人物出场次数最多的前 20 人。

'''
Python中的花括号{}:
代表dict字典数据类型,字典是Python中唯一内建的映射类型。
字典中的值没有特殊的顺序,但都是存储在一个特定的键(key)下。
键可以是数字、字符串甚至是元祖。
'''
import jieba
#定义一个集合,修正非人名,太多了,写不完了
excludes = {'将军','却说','三人','天下','东吴','今日','不敢','陛下','人马','后主','上马','不知','太守',
            '魏兵','于是','不可','荆州','二人','如此','不能','都督','一人','蜀兵','众将','只见','天子',
            '商议','如何','军士','左右','军马','引兵','次日','大喜','汉中','大叫','先主','此人','后人'}
txt=open("三国演义.txt","r",encoding='utf-8').read()
words=jieba.lcut(txt)
counts={}
for word in words:
    if len(word)==1:
        continue
    elif word in excludes:
        continue
    elif word=="玄德" or word == "玄德曰":
        word = "刘备"
    elif word == "孔明" or word == "孔明曰":
        word = "诸葛亮"
    elif word == "孟德" or word == "孟德曰":
        word = "曹操"
    elif word == "关公" or word == "云长":
        word = "关羽"
    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(20):
    word,count=items[i]
    print("{0:<10}{1:>5}".format(word,count))

python新手入门程序——实验6_第1张图片

最终还是有很多不是人名的词,还待改进

 

2、编写程序,模拟抓狐狸小游戏。假设一共有一排5个洞口,小狐狸最开始的时候在其中一个洞口,然后玩家随机打开一个洞口,如果里面有狐狸就抓到了。如果洞口里没有狐狸就第二天再来抓, 但是第二天狐狸会在玩家来抓之前跳到隔壁洞口里。

import random
n=5
#表示position只有一行数据第0行有n个数据
position=[0]*n
for i in range(n):
    position[i]=0
initPos=random.randint(0,n-1)
position[initPos-1]=1

def catchMe(initPos):
    maxsize = 10
    chance = 2
    while(maxsize):
        maxsize=maxsize-1
        try:
            x=input("打开一个洞口:")
            x=int(x)
            if not 0

 

你可能感兴趣的:(python)