Python 文件与数据格式化 练习题

目录

题目一

题目

代码

输出json文件

题目二

题目

代码


题目一

题目

        建立如图所示的test.csv文件,编程读该文件,将其转换成JSON数据格式文件,并以文件名"out.json"输出。

代码

#方法一:
import json
fr = open("D:\\test.csv","r",encoding='utf-8')
ls = []
for line in fr:
    line = line.replace("\n","")
    ls.append(line.split(','))
fr.close()

fw = open("test.json","w")
for i in range(1,len(ls)):
    ls[i]= dict(zip(ls[0],ls[i]))
json.dump(ls[1:],fw,sort_keys=True,indent=4,ensure_ascii=False)
fw.close()

# #方法二:
# import json
# with open("D:\\test.csv","r",encoding="UTF-8") as fr:
#     ls = []
#     for line in fr:
#         line = line.replace("\n", "")
#         ls.append(line.split(','))
#     fr.close()
# fw = open("test.json","w")
# for i in range(1,len(ls)):
#     ls[i]= dict(zip(ls[0],ls[i]))
# json.dump(ls[1:],fw,sort_keys=True,indent=4,ensure_ascii=False)
# fw.close()

输出json文件

题目二

题目

        编写程序制作英文学习字典,词典基本功能如下:
        (1) 程序读取源文件路径下的 txt 格式词典文件,若没有就创建一个。 词典文件存储方式为 “英文单词 中文单词”,每行仅有一对中英文释义;
        (2) 程序有添加功能,输入英文单词,如果没有可以添加中文释义,如果有就显示”已经存在,不能添加”;
        (3) 程序有查询功能,如果存在,则显示其中文释义,不存在就显示不存在;
        (4) 程序有正常退出的操作。

代码

# 方法一
# 字符串分行赋值
str = '''cat 猫
dog 狗
pig 猪
cow 奶牛'''
# 将str写入dic.txt文本中
with open('dic.txt', 'w', encoding='utf-8') as fw:
    fw.write(str)
    fw.close()
# 读入
with open('dic.txt', 'r', encoding='utf-8') as fr:
    Dic = {}
    for line in fr:
        # 将换行符用空的字符串代替,将英文单词和中文单词以空格隔开
        line = line.replace('\n', '').split(" ")
        # 将“英文单词 中文单词”添加到字典最后
        Dic.update({line[0]: line[1]})
# print(Dic)

while True:
    # 选择命令
    order = eval(input("请输入操作指令:1-查询  2-添加  3-退出"))
    if order == 1:
        word = input("请输入要查询的单词:")
        # 对dic.txt中的单词进行遍历
        if word in Dic.keys():
            print("{}的中文是:{}".format(word, Dic[word]))
        else:
            print("单词不存在,请添加该单词!")
        # for item in Dic.keys():
        #     if item == word:
        #         print("{}的中文是:{}".format(word, Dic[word]))
        #         break
        #     else:
        #         print("单词不存在,请添加该单词!")
        #         break
    elif order == 2:
        word = input("请输入要添加的单词:")
        for item in list(Dic.keys()):
            if item == word:
                print("单词已存在,请勿重复添加!")
                break
            else:
                explain = input("请输入该单词释义:")
                Dic.update({word: explain})
                fp = open("dic.txt", 'a', encoding='utf-8')
                # 添加单词步骤 1.行换  2.拿取最后一个字典的key和value
                fp.write("\n" + list(Dic.keys())[-1] + " " + Dic.get(list(Dic.keys())[-1]))
                fp.close()
                print("该单词添加成功,请继续操作!")
                break
    elif order == 3:
        break

# # 方法二
# import os
# keys = []
# dic = {}
#
# def readdict():
#     if os.path.exists("D:\\dictionary.txt"):
#         fr = open('D:\\dictionary.txt','r')
#     else:
#         fr = open('D:\\dictionary.txt','w+')
#     for line in fr:
#         line = line.replace("\n","")
#         v = line.split(':')
#         dic[v[0]]= v[1]
#         keys.append(v[0])
#     fr.close()
#
# def writedict(key,value):
#     with open('D:\\dictionary.txt','a')as fw:
#         fw.write(key+':'+value+'\n')
#
# def mydict():
#     n = input("请输入进入相应模块(添加,查询,退出)")
#     if n == "添加":
#         key = input("请输入英文单词:")
#         if key not in keys:
#             value =input("字典中未找到单词'{}'的中文释义,请输入该单词的中文意思,添加进字典中!".format(key))
#             dic[key] = value
#             keys.append(key)
#             writedict(key,value)
#         else:
#             print("单词'{}'已存在,不能添加".format(key))
#         return 0
#     elif n == "查询":
#         key = input("请输入英文单词:")
#         if key not in keys:
#             print("英文单词'{}'不在字典内".format(key))
#         else:
#             print(dic[key])
#         return 0
#     elif n == "退出":
#         return 1
#     else:
#         print("输入有误")
#         return 0
#
# def main():
#     readdict()
#     while True:
#         n = mydict()
#         if n == 1:
#             break
#         if n == 0:
#             continue
# main()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值