【问题标题】:Python Storing & Printing Data from a text filePython 从文本文件存储和打印数据
【发布时间】:2014-08-06 18:08:27
【问题描述】:

我正在尝试一个 Python 脚本,它从用户那里获取一系列特定字母(A、C、G、T)并打印 A、C、G 和 T 的百分比。

例如,如果用户键入 AGGTGACCCT 那么输出应该是 答:20 C: 30 克:30 时间:20

我对 Java 相当有经验,但对 Python 很陌生。我不会像在 Java 中那样使用扫描仪。我尝试通过参考库进行搜索,但无法真正弄清楚。

【问题讨论】:

    标签: java python


    【解决方案1】:

    collections.Counter 是一个非常方便的工具,值得在开始使用 python 时学习。

    from collections import Counter
    
    inp = input("Enter letters") # input() if using python 3
    
    l = len(inp.strip()) # get length of input string ,inp.strip() removes any whitespace, just use len(inp) if you want to include
    
    c = Counter(inp)
    
    for char in c:
        c[char] = c[char] * 100 / l  # don't need to cast as float for python 3
    print (c)
    Counter({'C': 30.0, 'G': 30.0, 'A': 20.0, 'T': 20.0})
    

    有一个模块csv 有一个DictWriter 可以将数据写入文件。

    【讨论】:

    • raw_input 要导入什么模块?
    • @Muffinman,它是python 2的内置,你不需要导入
    • 我没有使用 Python 2,这就是我想知道的原因。我正在使用最新版本的 3。
    • 我在旁边添加了一条注释,如果您使用的是 python 3,请使用 input()
    • 我刚刚注意到我发布了该评论,感谢您的帮助。
    【解决方案2】:

    您可以直接从标准输入流中读取,sys.stdin,如下所示:

    $ cat read.py 
    import sys
    
    userin = sys.stdin.read()
    print [c for c in userin]
    
    $ python read.py 
    HELLO
    ['H', 'E', 'L', 'L', 'O', '\n']
    

    然后您可以将文本文件通过管道传输到标准输入,例如:

    $ cat input.txt 
    HELLO
    $ python read.py < input.txt 
    ['H', 'E', 'L', 'L', 'O', '\n']
    

    或者,如果您想直接读取文件:

    >>> import io
    >>> with io.open('input.txt', mode='rb') as f:
    ...     print [c for c in f.read()]
    ... 
    ['H', 'E', 'L', 'L', 'O', '\n']
    

    【讨论】:

      【解决方案3】:

      如果您可以将序列保存在逗号分隔的文件 (csv) 中,那么您可以执行以下操作:

      import pandas as pd
      
      sequence = pd.read_csv(file_name)
      As = 0
      Cs = 0
      Gs = 0
      Ts = 0
      total = len(sequence)
      
      for letter in sequence:
          if letter == 'A':
              As += 1.0
          elif letter == 'C':
              Cs += 1.0
          elif letter == 'G':
              Gs += 1.0
          elif letter == 'T':
              Ts += 1.0
      
      percent_A = As/total
      percent_C = As/total
      percent_T = As/total
      percent_G = As/total
      

      或者:

      import pandas as pd
      
      sequence_list = []
      sequence = pd.read_csv(file_name)
      for letter in sequence:
          sequence_list.append(letter)
      
      As = sequence_list.count('A')
      Cs = sequence_list.count('C')
      Gs = sequence_list.count('G')
      Ts = sequence_list.count('T')
      
      total = len(sequence_list)
      
      percent_A = As/total
      percent_C = As/total
      percent_T = As/total
      percent_G = As/total
      

      这种通用结构也适用于 tsv。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 2018-12-30
        • 1970-01-01
        • 1970-01-01
        • 2018-04-04
        • 2021-12-22
        相关资源
        最近更新 更多