随性练习:python字典实现文本合并

主要用到,字典、字符串分割和连接、文件等操作

例如;有以下两个txt文本,要合并成一个

随性练习:python字典实现文本合并

代码:

address_book1 = {}
address_book2 = {}

def read_address():
     '''
     read content from txt
     :return
     '''
     with open("address1.txt","r") as f1:
         lines1 = f1.readlines()  #返回列表
         for line in lines1:
             line = line.strip()  #去空白
             content = line.split(",") #切割
             address_book1[content[0]] = content[1]
            
     with open("address2.txt","r") as f2:
         lines2 = f2.readlines()  #返回列表
         for line in lines2:
             line = line.strip()  #去空白
             content = line.split(",") #切割
             address_book2[content[0]] = content[1]

def merge_address(): #合并
     lines  = []
     header = "姓名\t     电话\t                邮箱\n"
     lines.append(header)
     for key in address_book1:
         line = ""
         if key in address_book2:
             line += "\t".join([key,address_book1[key],address_book2[key]]) #拼接
             line += "\n"
         else:
             line += "\t".join([key,address_book1[key],"********"]) #拼接
             line += "\n"
         lines.append(line)
     for key2 in address_book2:
         line = ""
         if key2 not in address_book1:
             line += "\t".join([key2,"************",address_book2[key2]]) #拼接
             line += "\n"
         lines.append(line)
     with open("new_address_book.txt","w",encoding="utf-8") as f3:
         f3.writelines(lines)
#         for i in lines:  #逐行写
#             f3.write(i)

if __name__ == "__main__":
     read_address()
#     print(address_book1)
#     print(address_book2)
     merge_address()

效果:

随性练习:python字典实现文本合并

上一篇:b00ks


下一篇:contenteditable可编辑div插入图片