首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在基因组中插入"N“的python代码

在基因组中插入"N“的python代码
EN

Stack Overflow用户
提问于 2016-02-12 05:20:14
回答 2查看 332关注 0票数 0

我的代码有问题,我试图读取一个fasta文件,即"chr1.fa",然后我有一个突变文件,如下所示

代码语言:javascript
运行
AI代码解释
复制
chr1    822979  822980  CLL6.08_1_snv   88.2    +
chr1    1052781 1052782 CLL6.08_2_snv   388.9   +
chr1    1216196 1216197 CLL6.08_3_snv   625 +
chr1    5053847 5053848 CLL6.08_4_snv   722.2   +
chr1    5735093 5735094 CLL6.08_5_snv   138.9   +

这是一个标签分隔文件,chr1作为第一列,+作为最后一列。我想在chr1.fa文件中插入一个N,使用第二个column.My代码中的位置,如下所示

代码语言:javascript
运行
AI代码解释
复制
     #!/usr/bin/python
     # Filename: mutation.py
      import sys , os
      import numpy as np
      import re

    #declaring the variables
     lst = ''
     chr_name = ''
     first_cord = ''
     second_cord = ''
     lstFirstCord = []
     sequence = ''
     human_genome = ''
     seqList = ''

    # Method to read the Genome file (file contains data for only one chromosome)
     def ReadgenomeCharacter():
     header = ' '
     seq = ' '
  try:
      human_genome = raw_input("Enter UCSC fasta file of human genome:")
      human_seq = open(human_genome, 'rw+')
      line = human_seq.readline()
 except:
    print 'File cannot be opened, wrong format you forgot something:', human_genome
    exit()
 while line:
    line = line.rstrip('\n')   
    if '>' in line:           
        header = line
    else:
        seq = seq + line
    line = human_seq.readline()
print header
print "Length of the chromosome is:",len(seq)
print "No. of N in the chromosome are:", seq.count("N")
return seq

  #Method to replace the characters in sequence string
    def ReplaceSequence():
    seqList = list(sequence)        
    for index, item in enumerate(lstFirstCord):
      if seqList[index] != "N":
        seqList[index] = "N"
        newSequence = ''.join(seqList) 
    return newSequence

   #Method to write to genome file
   def WriteToGenomeFile(newSequence):
      try:
       with open("chr1.fa", 'rw+') as f:
        old_human_seq = f.read()      
        f.seek(0)                      
        f.write(newSequence)          
        print "Data modified in the genome file"
        print "Length of the new chromosome is:",len(newSequence)
        print "No. of N in the new chromosome are:", newSequence.count("N")
except:
    print 'File cannot be opened, wrong format you forgot something:', human_genome
    exit()


   sequence = ReadgenomeCharacter()

   print "Here is my mutaiton file data"

   data = np.genfromtxt("CLL608.txt",delimiter ="\t", dtype=None,skip_header=0)        #Reading the mutation file CLL608.txt

    #Storing the mutation file data in a dictionary
     subarray = ({'Chr1' : data[data[:,0] == 'chr1'],'Chr2': data[data[:,0] == 'chr2'],'Chr3': data[data[:,0] == 'chr3'],
    'Chr4': data[data[:,0] == 'chr4'], 'Chr5': data[data[:,0] == 'chr5'],'Chr6': data[data[:,0] == 'chr6'],
    'Chr7': data[data[:,0] == 'chr7'], 'Chr8': data[data[:,0] == 'chr8'],'Chr9': data[data[:,0] == 'chr9'],
    'Chr10': data[data[:,0] == 'chr10'] , 'Chr11': data[data[:,0] == 'chr11'],'Chr12': data[data[:,0] == 'chr12'],
    'Chr13': data[data[:,0] == 'chr13'], 'Chr14': data[data[:,0] == 'chr14'],'Chr15': data[data[:,0] == 'chr15'],
    'Chr16': data[data[:,0] == 'chr16'],'Chr17': data[data[:,0] == 'chr17'],'Chr18': data[data[:,0] == 'chr18'],
    'Chr19': data[data[:,0] == 'chr19'], 'Chr20': data[data[:,0] == 'chr20'],'Chr21': data[data[:,0] == 'chr21'],
     'Chr22': data[data[:,0] == 'chr22'], 'ChrX': data[data[:,0] == 'chrX']})

    #For each element in the dictionary, fetch the first cord and pass this value to the method to replace the character on first chord with N in the genome file
    for the_key, the_value in subarray.iteritems():
    cnt = len(the_value)
    for lst in the_value:
    chr_name = lst[0]
    first_cord = int(lst[1])
    second_cord = int(lst[2])
    lstFirstCord.append(first_cord)            

   #Call the method to replace the sequence
   newSeq = ReplaceSequence()
   print "length :", len(newSeq)
   #Call the method to write new data to genome file
   WriteToGenomeFile(newSeq)
   `

我得到了这样的输出

代码语言:javascript
运行
AI代码解释
复制
Enter UCSC fasta file of human genome:chr1.fa
chr1 
Length of the chromosome is: 249250622
No. of N in the chromosome are: 23970000
Here is my mutaiton file data
length : 249250622
File cannot be opened, wrong format you forgot something: 

我们可以直接输入以下命令下载chr1.fa

代码语言:javascript
运行
AI代码解释
复制
rsync -avzP 
rsync://hgdownload.cse.ucsc.edu/goldenPath/hg19/chromosomes/chr1.fa.gz .

不知怎么的,我不能在序列中插入N,也不能将新的序列插入。如对改善守则有任何有价值的建议,我会很高兴:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-12 05:52:48

为了让您的生活变得更简单,您可能需要考虑使用Biopython在fasta中阅读并进行转换。

这里有一些文档可以让您开始使用http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc16

这是一些起始代码。

代码语言:javascript
运行
AI代码解释
复制
from Bio import SeqIO
handle = open("example.fasta", "rU")
output_handle = open("output.fasta", "w")
for record in SeqIO.parse(handle, "fasta"):
     print record.seq
handle.close()
output_handle.close()
票数 0
EN

Stack Overflow用户

发布于 2016-02-12 06:12:49

在查找文件目录和打开文件时,您可能会遇到一些问题。也就是说,一旦你有了文件数据,你的工作就相对容易了。您想要读取fasta文件,删除标题并将其转换为列表,然后将突变文件中的索引替换为"N“,然后重新创建fasta。以下是几个步骤:

代码语言:javascript
运行
AI代码解释
复制
from collections import defaultdict
chromosome = input("what chromosome are you editing? ")

# have all your file paths in order
mutations = path/to/mutations/file
fasta = path/to/fasta/file
newfile = path/to/new/file

# (1) get the mutations out of the mutations file into a list for each chrom
mutdict = defaultdict(list)
with open(mutations, "r") as f1:
    muts = f1.readlines()  # read all lines into list
    muts = [(x[0], int(x[1])) for x in muts]  # get the two columns you want

# (2) convert these to a dict
for (ch, pos) in muts:
    mutdict[ch].append(pos) 

# (3) get your fasta and convert it to a list
with open(fasta, "r") as f2:
    header = f2.readline()  # the first line is a header like ">chr1"
    bases  = f2.read().replace("\n", "")  # read all the bases and remove "\n"
bases = list(bases)  # turn the string into a list

# (4) now you loop through your mutations and change them to N in the fasta list
for mut in mutdict[chromosome]:
    bases[mut] = "N"

# (5) re-write the Fasta:
new_fasta = header
new_fasta = "\n".join("".join(bases[i:i + 50]) for i in xrange(len(bases)))
with open(newfile, "w") as out:
    out.write(new_fasta)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35363672

复制
相关文章
在LaTeX中插入python代码
老师突然要求交上去的论文需要在附录加上代码,奈何我使用的LaTeX模板只能高亮显示Matlab的代码,但是我写论文的时候绝大部分代码都是用Python写的在这里实名吐槽一下Matlab的数据处理功能这么拉跨,不知道为什么还被拿来当数据挖掘课的第一语言,没办法,只能找一个方法让LaTeX里面能高亮显示Python代码。
Hsinyan
2022/06/19
6.9K0
在LaTeX中插入python代码
看ASM在代码中的强势插入
前言 我之前写过一篇AOP的文章 看AspectJ在Android中的强势插入 是通过AspectJ来实现的,本篇是『巴掌』的投稿,他通过使用ASM来讲解了在Java和Android中的AOP方法,非常值得大家学习交流~ demo地址:https://github.com/JeasonWong/CostTime 需求 实际业务开发中有很多需要不改变原业务代码,而需额外增加一些包括各种统计的需求,如APM、无数据埋点等,也就是耳熟能详的AOP,本文以统计方法耗时为例,不使用Aspectj,采
用户1907613
2018/07/20
5.1K0
python在sqlite中插入数据
python通过引入sqlite的包,就能够直接操作sqlite数据库 import sqlite3 import math cx=sqlite3.connect("mydatabase.sqli
py3study
2020/01/06
4.1K0
在文章中插入广告代码投放广告
复制以下代码到functions.php 里使用即可 function themeInit($archive) { // 判断是否是文章,如果是就插入广告 $ad_code = ' <div>这是你的广告</div> '; if ($archive->is('single')) { $archive->content = prefix_insert_after_paragraph( $ad_code, 2, $archive->content );; } } // 插入广告所需的功能代码 function
团团生活志
2022/08/16
2.7K0
python在mysql中插入null空值
python在mysql中插入null空值 sql = “INSERT INTO MROdata (MmeUeS1apId) VALUES (%s)”%‘NULL’ %s没有引号,可以将“null”中null写进数据库,达到NULL值效果。
kirin
2020/12/03
8.5K0
在latex中写python代码
大家都知道,python现在用的是越来越多了,功能强大,易于上手,如果能借助于其强大的绘图功能,latex岂不碉堡了?
py3study
2020/01/07
2K0
在latex中写python代码
看AspectJ在Android中的强势插入
什么是AOP AOP是Aspect Oriented Programming的缩写,即『面向切面编程』。它和我们平时接触到的OOP都是编程的不同思想,OOP,即『面向对象编程』,它提倡的是将功能模块化,对象化,而AOP的思想,则不太一样,它提倡的是针对同一类问题的统一处理,当然,我们在实际编程过程中,不可能单纯的安装AOP或者OOP的思想来编程,很多时候,可能会混合多种编程思想,大家也不必要纠结该使用哪种思想,取百家之长,才是正道。 那么AOP这种编程思想有什么用呢,一般来说,主要用于不想侵
用户1907613
2018/07/20
2.7K0
PPT 中插入域代码公式的方法
注意: 我们希望能够尽快以你的语言为你提供最新的帮助内容。 本页面是自动翻译的,可能包含语法错误或不准确之处。我们的目的是使此内容能对你有所帮助。可以在本页面底部告诉我们此信息是否对你有帮助吗? 请在此处查看本文的 英文版本 以便参考。
全栈程序员站长
2022/09/05
3.9K0
python中时间的加n和减n运算
   好多朋友都遇到过python推算时间的问题,有些把时间转换成整数做推算,这样遇到特殊的时间和日期就会出现错误,在python中时间的推算很简单,主要就是用到datetime.timedelta方法,进行时间的加n减n运算:
py3study
2020/01/08
1.7K0
怎样在Visio中插入大括号?
在标注类形状中就可以找到大括号了。可以看到,系统默认配置了两种大括号类型:双侧大括号和单侧大括号,大家可以根据实际需要自己选择。
狼啸风云
2021/05/17
13.1K0
怎样在Visio中插入大括号?
在 LaTeX 中插入图片「建议收藏」
原  文:Inserting Images 译  者:Xovee 翻译时间:2020年9月18日
全栈程序员站长
2022/09/05
17.6K0
在 LaTeX 中插入图片「建议收藏」
使用insert () 在MongoDB中插入数组
“insert”命令也可以一次将多个文档插入到集合中。下面我们操作如何一次插入多个文档。
MongoDB中文社区
2020/02/19
8K0
使用insert () 在MongoDB中插入数组
Chromedriver 在 Python 中查看源代码的方法
然后进行初始化: chrome = Chrome(service=Service(r"C:\Users\yhu\Downloads\chromedriver-win64\chromedriver-win64\chromedriver.exe"))
HoneyMoose
2023/09/18
2590
Chromedriver 在 Python 中查看源代码的方法
关于Python中No module n
错误信息:ModuleNotFoundError: No module named 'requests'
py3study
2020/01/06
8170
numpy在cs231n中的应用
0.作者的话1.访问数组2.broadcast机制3.np.bincount()4.np.argmax()5.联合求解6.求取精度7.作者的话
公众号guangcity
2019/09/20
2.5K0
numpy在cs231n中的应用
C# 在 webBrowser 光标处插入 html代码 .
private void BtnInsertMedia_Click(object sender, EventArgs e)         {             InWord frm = new InWord("请填入视频地址(后缀必须是.swf):");             frm.ShowDialog();             if (frm.Value != null && frm.Value != "")             {                 IHTMLDocum
跟着阿笨一起玩NET
2018/09/18
1.5K0
Starlight:帮助Python代码在Go中运行的工具
I’d like to announce starlight - https://github.com/starlight-go/starlight.
李海彬
2018/12/26
2.2K0
用 VBA 在 PPT 中批量插入图片
网上用 VBA 操作 EXCEL的 示例很多,但用 VBA 操作 PPT 的示例很少,而且通常有不少错误或者版本老旧的地方。
用户6021899
2023/08/09
1.2K1
用 VBA 在 PPT 中批量插入图片
文本或代码中 \n 和 \r 的区别
在 ASCII 码中,我们会看到有一类不可显示的字符,叫控制字符,其中就包含\r 和 \n 等控制字符。
DeROy
2020/12/02
5K0
在评论输入框中插入表情
最近在做一个后台管理系统,要求可以对前台用户的作品进行评论,而评论要可以输入表情,常规的文字输入框都是用的文本域textarea来做的,但这种输入框只能输入文字,没有办法输入表情图标,这个时候可编辑div就能起到作用了,那么如何在可编辑的div中插入表情呢?
越陌度阡
2020/11/26
4.2K0

相似问题

在StackOverflow中插入python代码

12

如何在基因组数据中插入互补碱基?

13

在n个部分后插入广告代码?

33

python中的n元树插入算法

128

在bash脚本中插入python代码

39
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档