你提到的Python,Perl和awk中。
在所有三者中,這個想法都是一樣的:使用散列來存儲值。
哈希與數組類似,除了每個條目都使用鍵索引,而不是位置。在一個散列中,只能有一個關鍵字。因此,哈希用於檢查值是否曾經出現過。下面是一個簡單的Perl例如:
my %value_hash;
for my $value (qw(one two three one three four)) {
if (exists $value_hash{$value}) {
print "I've seen the value $value before\n";
}
else {
print "The value of $value is new\n";
$value_hash{$value} = 1;
}
}
這將打印出:
The value of one is new
The value of two is new
The value of three is new
I've seen the value of one before
I've seen the value of three before
The value of four is new
首先,你需要兩個循環:一個遍歷所有文件,另一個遍歷的每一行特定的文件。
for my $file_name (@file_list) {
open my $file_fh, "<", $file_name
or die qw(File $file_name doesn't exist);
while (my $line = <$file_fh>) {
chomp $line;
...
}
}
接下來,我們會爲每個氨基酸和那些氨基酸追蹤散列的總和介紹哈希:
use strict;
use warnings;
use autodie;
my %total_amino_acids;
my @file_list = qw(file1 file2); #Your list of files
for my $file_name (@file_list) {
open my $file_fh, "<", $file_name;
my %seen_amino_acid_before; # "Initialize" hash which tracks seen
while (my $line = <$file_fh>) {
chomp $line;
my ($location, $amino_acid) = split $line;
if (not %seen_amino_acid_before{$amino_acid}) {
$total_amino_acids{$amino_acid} += 1;
}
}
}
現在,我假設當你說獨特 ,你只是在談論氨基酸而不是位置。 split
正在分裂這兩個值,我只看着氨基酸。如果位置也很重要,則必須將其包含在第%seen_amino_acid_before
個散列的密鑰中。這是棘手的,因爲我可以想象以下內容:
54 LEU
54 LEU
054.00 LEU
這些是不同的字符串,但都具有相同的信息。你想要確保你標準化位置/氨基酸密鑰。
while (my $line = <$file_fh>) {
chomp $line;
my ($location, $amino_acid) = split $line;
my $amino_acid_key = sprinf "%04d-%s", $location, uc $amino_acid;
if (not %seen_amino_acid_before{$amino_acid_key}) {
$total_amino_acids{$amino_acid} += 1;
}
}
在上面,我創建了一個$amino_acid_key
。我使用sprintf
將我的數字部分格式化爲零填充小數,氨基酸爲大寫。這樣:
54 LEU
54 leu
054.00 Leu
都將是關鍵0054-LEU
。這樣,數據輸入到文件中的方式不會影響結果。這可能是一個完全不必要的步驟,但應該始終考慮。例如,如果您的數據是由計算機生成的,那麼這可能不是問題。如果您的數據是在半夜中由一羣過度勞動的研究生輸入的,那麼您可能需要擔心格式。
現在,所有你需要的是一個循環讀取數據:我以前printf
幫助格式化總計
for my $amino_acid (sort keys %total_amino_acids) {
printf "total no:of %4s - %4d\n", $amino_acid, $total_amino_acids{$amino_acid};
}
通知,所以他們會排起長隊。
'而TRUE':你需要一個'break'陳述或者你會得到一個無限循環。 – 2013-04-07 04:12:02