python 中实现文本的转置

 

001、

root@PC1:/home/test2# ls
outcome.ped  test.py
root@PC1:/home/test2# cat outcome.ped                            ## 测试数据
1       G       G       C       C       G       G
2       G       G       G       C       G       G
3       G       G       C       C       G       G
4       G       G       C       C       G       G
5       G       G       C       C       G       G
6       G       G       C       C       G       G
root@PC1:/home/test2# cat test.py                                ## 转置脚本
#!/usr/bin/pyhon

in_file = open("outcome.ped", "r")
out_file = open("result.ped", "w")

lines = in_file.readlines()                                
length=len(lines[0].split())                                 ## 统计原始文件列数

result_dict = {}

for i in range(0, length):
    result_dict[i] = []                                      ## 生成长度为列数的字典

for i in lines:
    lines = i.strip().split()
    for j in range(0,length):
        result_dict[j].append(lines[j])                      ## 依次向字典的值中添加元素

for i in result_dict.keys():
    print('\t'.join(result_dict[i]), file = out_file)

in_file.close()
out_file.close()
root@PC1:/home/test2# python test.py
root@PC1:/home/test2# ls
outcome.ped  result.ped  test.py
root@PC1:/home/test2# cat result.ped                        ## 转置结果
1       2       3       4       5       6
G       G       G       G       G       G
G       G       G       G       G       G
C       G       C       C       C       C
C       C       C       C       C       C
G       G       G       G       G       G
G       G       G       G       G       G

 

参考:https://mp.weixin.qq.com/s?__biz=MzIxNzc1Mzk3NQ==&mid=2247492008&idx=8&sn=6c9d5183ed07c13b7c76472ecbdbd29e&chksm=97f651b0a081d8a663ce46bb44b125b194b797398a4d3a347bb5494d1c4387aae567a9453184&scene=178&cur_album_id=2403674812188688386#rd

 

posted @ 2022-08-05 16:13  小鲨鱼2018  阅读(82)  评论(0编辑  收藏  举报