【Python】基础练习题_文件及数据格式化

(1)从键盘输入一些字符,逐个把它们写到磁盘文件"test1.txt"上,直到输入一个#为止。

file_name = "test1.txt"

with open(file_name, "w") as file:
    while True:
        char = input("请输入字符:")
        if char == "#":
            break
        file.write(char)

print("字符已写入文件", file_name)

(2)从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test2.txt"中保存。

file_name = "test2.txt"

string = input("请输入字符串:")
converted_string = string.upper()

with open(file_name, "w") as file:
    file.write(converted_string)

print("转换后的字符串已保存到文件", file_name)

(3)将上述(1)和(2)中的两个磁盘文件"test1.txt"和"test2.txt",件中的信息合并(并按字母顺序排列处理),输出到一个新文件"test_merge.txt"中。

file1_name = "test1.txt"
file2_name = "test2.txt"
merge_file_name = "test_merge.txt"

with open(file1_name, "r") as file1, open(file2_name, "r") as file2:
    content1 = file1.read()
    content2 = file2.read()

merged_content = content1 + content2
sorted_content = ''.join(sorted(merged_content))

with open(merge_file_name, "w") as merge_file:
    merge_file.write(sorted_content)

print("合并后的信息已保存到文件", merge_file_name)

(4)制作英文学习词典。编写程序制作英文学习词典,词典有3个基本功能:添加、查询和退出。程序读取源文件路径下的txt格式词典文件,若没有就创建一个。词典文件存储方式为“英文单词 中文单词”,每行仅有一对中英释义。程序会根据用户的选择进入相应的功能模块,并显示相应的操作提示。当添加的单词已存在时,显示“该单词已添加到字典库”;当查询的单词不存在时,显示“字典库中未找到这个单词”。用户输入其他选项时,提示“输入有误”。
要求分别定义两个函数实现从字典中查询单词和向字典中添加单词的功能。

import os

def add_word(dictionary):
    word = input("请输入要添加的英文单词:")
    if word.lower() in dictionary:
        print("该单词已添加到字典库")
    else:
        translation = input("请输入该单词的中文释义:")
        dictionary[word.lower()] = translation
        print("单词添加成功")

def search_word(dictionary):
    word = input("请输入要查询的英文单词:")
    if word.lower() in dictionary:
        print("中文释义:", dictionary[word.lower()])
    else:
        print("字典库中未找到这个单词")

def main():
    file_name = "dictionary.txt"
    dictionary = {}

    if os.path.exists(file_name):
        with open(file_name, "r") as file:
            for line in file:
                line = line.strip()
                word, translation = line.split(" ")
                dictionary[word.lower()] = translation

    while True:
        print("欢迎使用英文学习词典!请选择操作:")
        print("1. 添加单词")
        print("2. 查询单词")
        print("3. 退出")

        choice = input("请输入选项编号:")
        if choice == "1":
            add_word(dictionary)
        elif choice == "2":
            search_word(dictionary)
        elif choice == "3":
            with open(file_name, "w") as file:
                for word, translation in dictionary.items():
                    file.write(word + " " + translation + "\n")
            print("词典已保存,感谢使用!")
            break
        else:
            print("输入有误,请重新输入选项编号")

main()

(5)图片文件压缩。使用PIL库对图片进行等比例压缩,无论压缩前文件大小如何,压缩后文件小于10kB‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬
提示:size=os.path.getsize(path) #获取指定路径文件占用存储空间的大小。据此计算压缩比。再去调整图片缩放。
Im=im.resize((sizex,sizey)) #将图像im缩放到指定大小。
要求:至少有指定压缩比的图片压缩函数和主函数。

import os
from PIL import Image


def image_compress(file_path, compress_ratio):
    # 获取原始图片尺寸
    im = Image.open(file_path)
    original_size = os.path.getsize(file_path)
    width, height = im.size

    # 计算目标图片尺寸
    target_width = int(width * compress_ratio)
    target_height = int(height * compress_ratio)

    # 缩放图片尺寸
    resized_im = im.resize((target_width, target_height))

    # 保存压缩后的图片
    resized_im.save("compressed_image.jpg", optimize=True, quality=95)
    compressed_size = os.path.getsize("compressed_image.jpg")

    # 检查压缩比是否满足要求
    if compressed_size / original_size > 0.1:
        print("无法将图片压缩到指定大小以下。")
    else:
        print("图片压缩成功。压缩前大小: {} bytes,压缩后大小: {} bytes。".format(original_size, compressed_size))


# 测试压缩函数
image_compress("original_image.jpg", 0.1)
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
回答: 这里提供了三个Python的for循环练习题。第一个练习题是打印九九乘法表,使用嵌套的for循环来控制行和列,通过字符串格式化输出乘法表的结果。\[1\]第二个练习题是判断一个字符串是否由数字、字母和下划线组成,通过遍历字符串中的每个字符,使用条件判断来判断字符是否符合要求。如果有任何一个字符不符合要求,则输出False,否则输出True。\[1\]第三个练习题是求一个整数的阶乘,通过for循环来计算阶乘的结果。\[2\]另外还有一个练习题是求两个数的最大公约数和最小公倍数,通过for循环和条件判断来找出最大公约数,并使用公式计算最小公倍数。\[3\]这些练习题可以帮助提高对for循环的理解和应用能力。 #### 引用[.reference_title] - *1* [Python基础练习题-for循环](https://blog.csdn.net/weixin_43219844/article/details/97615310)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Python之循环语句:for及相关练习题](https://blog.csdn.net/weixin_44826014/article/details/90577727)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小秀_heo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值