Python存储&从文本文件打印数据

时间:2014-08-06 18:08:27

标签: java python

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

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

我对Java很有经验,但对Python很新。我不像在Java中那样使用扫描仪。我试着在参考图书馆中搜索,但无法解决任何问题。

3 个答案:

答案 0 :(得分:0)

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能够将数据写入文件。

答案 1 :(得分:0)

您可以直接从标准输入流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']

然后你可以将文本文件传递给stdin,例如:

$ 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']

答案 2 :(得分:0)

如果您可以将序列保存在逗号分隔文件(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

这种一般结构也适用于tsvs。