武汉理工大学python123实验——文件

一、 概览

二、参考代码

1. 大学排行榜分析  #126373

# --------      -------    --------
# @Author : 赵广辉   
# @Contact: vasp@qq.com
# @Company: 武汉理工大学
# @Version: 1.0
# @Modify : 2022/06/13 11:33
# Python程序设计基础,赵广辉,高等教育出版社,2021
# Python程序设计基础实践教程,赵广辉,高等教育出版社,2021
# --------      -------    --------

def read_file(file,m):
    """读文件中的学校名到列表中,返回前m个记录的学校集合"""
    with open(file,'r',encoding='utf-8') as f:
        a = list(f.readlines())
        #print(a)
        ###########关键代码
        ls = [list(i.split())[1] for i in a]
        #print(ls)
        return ls[0:m]


def either_in_top(alumni, soft):
    """接收两个排行榜前m高校名字集合,
    获得在这两个排行榜中均在前m个记录的学校名,按照学校名称排序,
    返回排序后的列表
    """
    ls = []
 
    for i in alumni:
        if i in soft:
            ls.append(i)
    ls.sort()
    return ls




def all_in_top(alumni, soft):
    """接收两个排行榜前m高校名字集合,
    获得在两个榜单中名列前m的所有学校名,按照学校名称排序,
    返回排序后的列表
    """
    t = alumni+soft
    s = list(set(t))
    s.sort()
    return s
    


def only_alumni(alumni, soft):
    """接收两个排行榜前m高校名字集合,
    获得在alumni榜单中名列前m但soft榜单中未进前m的学校名,
    按照学校名称排序,返回排序后的列表
    """
    ls = []
    for i in alumni:
        if i not in soft:
            ls.append(i)
    ls.sort()
    return ls


def only_once(alumni, soft):
    """接收两个排行榜前m高校名字集合,
    获得在alumni和soft榜单中名列前m,但不同时出现在两个榜单的学校名,
    按照学校名称排序,返回排序后的列表
    """
    ls = []
    for i in alumni:
        if i not in soft:
            ls.append(i)
    for i in soft:
        if i not in alumni:
            ls.append(i)
    ls.sort()
    return ls



def judge(n):
    if n in '1234':
        m=int(input())
        alumni_set = read_file('./alumni.txt',m)
        soft_set = read_file('./soft.txt',m)
        if n=='1':
            either_rank = either_in_top(alumni_set, soft_set)
            print(f'两榜单中均名列前{m}的学校:')
            print(either_rank)
        elif n=='2':
            all_rank = all_in_top(alumni_set, soft_set)
            print(f'两榜单名列前{m}的所有学校:')
            print(all_rank)
        elif n=='3':
            only_in_alumni_rank = only_alumni(alumni_set, soft_set)
            print(f'alumni中名列前{m},soft中未进前{m}的学校:')
            print(only_in_alumni_rank)
        elif n=='4':
            alumni_soft_rank = only_once(alumni_set, soft_set)
            print(f'不同时出现在两个榜单前{m}的学校:')
            print(alumni_soft_rank)
    else:
        print('Wrong Option')
        

if __name__ == '__main__':
    num = input()
    judge(num)
    

2. 简易英汉字典 #126645

# --------      -------    --------
# @File   : 简易英汉词典.py 
# @Author : 赵广辉   
# @Contact: vasp@qq.com
# @Company: 武汉理工大学
# @Version: 1.0
# @Modify : 2021/12/06 23:39
# Python程序设计基础,高等教育出版社
# 代码量1.5-2小时
# --------      -------    --------
import string


def create_dict(filename):
    """接收表示文件名的字符串参数,读文件中的单词及释义,以单词为键,其他部分为值创建字典。
    多个释义间可能是逗号或空格分隔,但单词与第一个释义间至少有一个空格,
    将文件每一行根据空格切分一次,切分结果分别作为键和值创新字典。
    返回字典。
    """
    ### 使用字典推导式!!!
    ### 或者用二元组列表d = dict([(1,2),(b,9),(a,3)])
    with open(filename,'r',encoding='utf-8') as f:
        ls=[line.strip().split(maxsplit=1) for line in f]
        dic={k:v for k,v in ls}
    return dic
        
        



def translate(dic, word):
    """接收两个参数,第一个是读文件创建的字典,第二个参数为要查询的单词,字符串
    根据文件创建的字典,从中查询单词word,
    如果查询单词存在,元组形式返回词与词的释义;
    如果查询不存在,返回'这个词我不明白'
    """
    word=word.lower()
    return word,dic.get(word,'这个词我不明白')



def sentence_to_words():
    """调用此函数时,先输出提示信息'请输入查询的句子:'
    用户输入欲翻译的句子
        若输入非空时,先将"n't"替换为 ' not'、"'s"替换为 ' is',再将标点符号替换为空格。
    根据空格将句子切分为单词的列表,调用translate逐个单词进行翻译。
    用户可重复多次输入,每输入一名翻译一句,
    若直接输入回车时,输出'查询结束,正在退出...'。然后结束程序。
    """
    while 1:
        #print('请输入查询的句子:',end='')
        s=input('请输入查询的句子:')
        if len(s)==0:
            print('查询结束,正在退出...')
            break
        s=s.replace("n't", ' not')
        s=s.replace("'s", ' is')
        for x in string.punctuation:                # 其他标点符号替换为空格
            s = s.replace(x, ' ')
        ls=s.split()
        for word in ls:
            print(" ".join(translate(word_dic,word)))
        



def translate_word():
    """调用此函数时,先输出提示信息:'请输入查询的单词:'
    用户可循环输入欲翻译的单词,若直接输入回车时,输出'查询结束,正在退出...'。
    输入非空时输出翻译结果
    """
    while 1:
        #print('请输入查询的单词:',end='')
        word=input('请输入查询的单词:')
        if len(word)==0:
            print('查询结束,正在退出...')
            break
        print(' '.join(translate(word_dic,word)))



if __name__ == '__main__':
    file = './dict.txt'           # 表示文件名的字符串,表示位于当前路径下的'dict.txt'文件
    word_dic = create_dict(file)  # 调用函数返回字典类型的数据
    print('载入字典数据成功!查询单词请输入“1”,查询句子请输入“2”')
    choice = input()              # 输入操作选项
    if choice == '1':
        translate_word()          # 翻译单词
    elif choice == '2':
        sentence_to_words()       # 翻译句子
    else:
        print('输入错误,请重新运行程序!')

3. 数据统计 #1892

import random

a,b=map(int,input().split())

random.seed(10)

ls = [random.randint(a,b) for i in range(100)]
#[print(i,ls.count(i)) for i in sorted(set(ls))]

for i in range(a,b+1):

    if ls.count(i)!=0:

        print(i,ls.count(i))

4. 罗马数字转换 #72854

d = {'I': 1, 'IV': 3, 'V': 5, 'IX': 9, 'X': 10, 'XL': 30, 'L': 50, 'XC': 80, 'C': 100, 'CD': 300, 'D': 500, 'CM': 800, 'M': 1000}
s = input()
count=0
p=-1
for i in range(len(s)):
    if i==p:
        continue
    if i<len(s)-1 and s[i]+s[i+1] in d.keys():
        count+=d[s[i]+s[i+1]]
        p=i+1
    else:
        count+=d[s[i]]
print(count)
    

5. 词频统计 # 133163

# --------      -------    --------
# @Author : 赵广辉   
# @Contact: vasp@qq.com
# @Company: 武汉理工大学
# @Version: 1.0
# @Modify : 2022/06/13 11:33
# Python程序设计基础,赵广辉,高等教育出版社,2021
# Python程序设计基础实践教程,赵广辉,高等教育出版社,2021
# --------      -------    --------

import string


def read_file(file):
    """接收文件名为参数,将文件中的内容读为字符串,
    只保留文件中的英文字母和西文符号,
    过滤掉中文(中文字符及全角符号Unicode编码都大于256)
    将所有字符转为小写,
    将其中所有标点、符号替换为空格,返回字符串
    """
    with open(file, 'r', encoding='utf-8') as f:
        txt = f.read()
    s=''
    for c in txt:
        if ord(c)>256:
            s=s+''
        elif c in string.punctuation:
            s=s+' '
        else:
            s=s+c 
    return s.lower()



def count_of_words(txt):
    """接收去除标点、符号的字符串,统计并返回其中单词数量和不重复的单词数量"""
    ls=txt.split()
    return len(ls),len(set(ls))



def word_frequency(txt):
    """接收去除标点、符号的字符串,统计并返回每个单词出现的次数
    返回值为字典类型,单词为键,对应出现的次数为值"""
    ls=txt.split()
    dic={k:ls.count(k) for k in set(ls)}
    return dic



def top_ten_words(frequency, cnt):
    """接收词频字典,输出出现次数最多的cnt个单词及其出现次数"""
    ls = sorted(frequency.items(), key=lambda x: x[1], reverse=True)
    for word, counts in ls[:cnt]:
        print(word, counts)



def top_ten_words_no_excludes(frequency, cnt):
    """接收词频字典,去除常见的冠词、代词、系动词和连接词后,输出出现次数最多的
    cnt个单词及其出现次数,需排除的单词如下:
    excludes_words = ['a', 'an', 'the', 'i', 'he', 'she', 'his', 'my', 'we',
    'or', 'is', 'was', 'do', 'and', 'at', 'to', 'of', 'it', 'on', 'that', 'her',
    'c','in', 'you', 'had','s', 'with', 'for', 't', 'but', 'as', 'not', 'they', 
    'be', 'were', 'so', 'our','all', 'would', 'if', 'him', 'from', 'no', 'me', 
    'could', 'when', 'there','them', 'about', 'this', 'their', 'up', 'been', 
    'by', 'out', 'did', 'have']
    """
    excludes_words = ['a', 'an', 'the', 'i', 'he', 'she', 'his', 'my', 'we',
    'or', 'is', 'was', 'do', 'and', 'at', 'to', 'of', 'it', 'on', 'that', 'her',
    'c','in', 'you', 'had','s', 'with', 'for', 't', 'but', 'as', 'not', 'they', 
    'be', 'were', 'so', 'our','all', 'would', 'if', 'him', 'from', 'no', 'me', 
    'could', 'when', 'there','them', 'about', 'this', 'their', 'up', 'been', 
    'by', 'out', 'did', 'have']
    for k in excludes_words:
        frequency.pop(k)
    ls = sorted(frequency.items(), key=lambda x: x[1], reverse=True)
    for word, counts in ls[:cnt]:
        print(word, counts)



# 取消这段和代码最后二行注释可以绘制词云,仅供参考
# def draw_cloud(frequency):
#     """绘制词云,传入参数为词频,设定图片的宽度600,高度400,背景白色、字体最大值150、图片边缘为5。"""
#     wc = WordCloud(max_words=80,              # 设置显示高频单词数量
#                   width=600,                 # 设置图片的宽度
#                   height=400,                # 设置图片的高度
#                   background_color='White',  # 设置背景颜色
#                   max_font_size=150,         # 设置字体最大值
#                   margin=5,                  # 设置图片的边缘
#                   scale=1.5)                 # 按照比例进行放大画布,如设置为1.5,则长和宽都是原来画布的1.5倍。
#     wc.generate_from_frequencies(frequency)   # 根据文本内容直接生成词云
#     plt.imshow(wc)                            # 负责对图像进行处理,并显示其格式,但是不能显示。
#     plt.axis("off")                           # 不显示坐标轴
#     wc.to_file('My Cheese.png')               # 词云保存为图片
#     plt.show()                                # 显示图像



if __name__ == '__main__':
    filename = 'Who Moved My Cheese.txt'  # 文件名
    content = read_file(filename)  # 调用函数返回字典类型的数据
    frequency_result = word_frequency(content)  # 统计词频
    cmd = input()
    if cmd == '1':
        n = int(input())
        print(content[:n])
    elif cmd == '2':
        amount_results = count_of_words(content)
        print('文章共有单词{}个,其中不重复单词{}个'.format(*amount_results))
    elif cmd == '3':
        n = int(input())
        top_ten_words(frequency_result, n)
    elif cmd == '4':
        n = int(input())
        top_ten_words_no_excludes(frequency_result, n)
        # frequency_no_excludes = top_ten_words_no_excludes(frequency_result)
        # draw_cloud(frequency_no_excludes)
        
        

6. 商品房数据统计 #136866

with open('wuhan2021s1.csv','r',encoding='GBK') as f:

    ls=[line.strip().split(",")for line in f][1:]

district={x[1] for x in ls}

lss=ls

n=input()

if n=="规模升序":

    lss.sort(key=lambda x:eval(x[-1]))

    for line in lss:

        print(" ".join(line))

elif n=="规模降序":

    lss.sort(key=lambda x:eval(x[-1]),reverse=True)

    for line in lss:

        print(" ".join(line))

elif n in district:
    lss=[x for x in ls if x[1]==n]

    for line in lss:
 
       print(" ".join(line))

    print("{:.2f}平方米".format(sum([eval(x[-1]) for x in lss])))

elif n=="总规模":

    print("{:.2f}平方米".format(sum([eval(x[-1]) for x in ls])))

else:

    print("错误输入")

7. 统计文本中单词数  # 2545

file=input()

with open(file,'r',encoding='utf-8') as f:

    txt=f.read()

for c in '!"#$%&()*+,./:;<=>?@[\]^_{|}~\n':
 
    txt=txt.replace(c," ")

print(len(txt.split()))

8. 2019慈善排行 # 114813

with open("2019Charity.csv","r",encoding="utf-8")as f:

    ls=[line.strip().split(",") for line in f][1:]

province={x[3] for x in ls}

s=input()

if s.lower()=="total":

    lss=[eval(x[-1])for x in ls]

    print('Total:{}万元'.format(sum(lss)))

elif s.isdigit() and int(s) in range(1,101):

    lss=[x for x in ls if x[0]==s]

    for line in lss:

        print(" ".join(line))

elif s in province:

    lss=[x for x in ls if x[-3]==s]

    for line in lss:

        print(" ".join(line[:4]))

else:

    print("No Record")

  • 11
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值