[英]Python Storing & Printing Data from a text file
我正在嘗試一個Python腳本,該腳本從用戶那里獲取某些字母的序列(A,C,G和T),並打印A,C,G和T的百分比。
例如,如果用戶鍵入AGGTGACCCT,則輸出應為A:20 C:30 G:30 T:20
我對Java有相當的經驗,但是對Python還是陌生的。 我沒有像在Java中那樣使用掃描儀。 我嘗試搜索參考庫,但無法真正找出任何答案。
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})
有一個具有DictWriter的模塊csv
,該DictWriter能夠將數據寫入文件。
您可以直接從標准輸入流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']
如果您可以將序列保存在以逗號分隔的文件(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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.