【问题标题】:Python: object of type '_io.TextIOWrapper' has no len()Python:“_io.TextIOWrapper”类型的对象没有 len()
【发布时间】:2018-07-20 19:20:32
【问题描述】:

我在运行我的代码时不断收到错误:

TypeError: '_io.TextIOWrapper' 类型的对象没有 len() 函数

如何让它打开/读取文件并通过循环运行它?

这是我要导入的文件的链接: download link of the DNA sequence

    def mostCommonSubstring():
        dna = open("dna.txt", "r")
        mink = 4
        maxk = 9
        count = 0
        check = 0
        answer = ""
        k = mink
        while k <= maxk:
            for i in range(len(dna)-k+1):
                sub = dna[i:i+k]
                count = 0
                for i in range(len(dna)-k+1):
                    if dna[i:i+k] == sub:
                        count = count + 1
                if count >= check:
                    answer = sub
                    check = count
            k=k+1
        print(answer)
        print(check)

【问题讨论】:

  • 你不能打电话给len(dna)
  • 文件对象没有len。它们也不能被切片/索引,即dna[i:i+k] 也会失败

标签: python string function loops


【解决方案1】:

由于您打开文本文件的方式而出现问题。 您应该将dna = dna.read() 添加到您的代码中。 所以你的最终代码应该是这样的:

def mostCommonSubstring():
    dna = open("dna.txt", "r")
    dna = dna.read()
    mink = 4
    maxk = 9
    count = 0
    check = 0
    answer = ""
    k = mink
    while k <= maxk:
        for i in range(len(dna)-k+1):
            sub = dna[i:i+k]
            count = 0
            for i in range(len(dna)-k+1):
                if dna[i:i+k] == sub:
                    count = count + 1
            if count >= check:
                answer = sub
                check = count
        k=k+1
    print(answer)
    print(check)

【讨论】:

    【解决方案2】:

    @tfabiant:我建议使用此脚本来读取和处理 DNA 序列。 要运行此代码,请在终端中:python readfasta.py fastafile.fasta

    import string, sys
    ##########I. To Load Fasta File##############
    file = open(sys.argv[1]) 
    rfile = file.readline()
    seqs = {} 
    ##########II. To Make fasta dictionary####
    tnv = ""#temporal name value
    while rfile != "":
        if ">" in rfile:
            tnv = string.strip(rfile)
            seqs[tnv] = ""
        else:
            seqs[tnv] += string.strip(rfile)    
        rfile = file.readline()
    ##############III. To Make Counts########
    count_what = ["A", "T", "C", "G", "ATG"]
    for s in seqs:
        name = s
        seq = seqs[s]
        print s # to print seq name if you have a multifasta file
        for cw in count_what:
            print cw, seq.count(cw)# to print counts by seq
    

    【讨论】:

      猜你喜欢
      • 2015-01-21
      • 2021-03-03
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2016-06-06
      相关资源
      最近更新 更多