0

我正在尝试制作多维散列但收效甚微。

我已将我正在使用的脚本放在下面(注意:我正在使用 bio gem。)

#!/usr/bin/env ruby
require 'bio'

def make_hash(input_file)
  input_read = Hash.new
  biofastafile = Bio::FlatFile.open(Bio::FastaFormat, input_file) 
  biofastafile.each_entry do |entry|
    #### If I uncomment the below line, it gives me 2D hash ###
    ####   input_read[entry.definition] = entry.aaseq
    ####
    input_read.map { |maps|
      id_start, id_end = entry.definition.split('-')
      signalp, seq_end = entry.aaseq.split('-')

     {
       :id_start => id_start,
       :id_end => id_end,
       :signalp => signalp,
       :seq_end => seq_end,
       } 
     }
    end
    return input_read
  end

hash = make_hash("./sample.txt")

puts hash
# puts hash[:id_start]

样本.txt

>isotig00003_f6_8 - Signal P Cleavage Site => 11:12
MMHLLCIVLLL-KWWLLL
>isotig00003_f6_9 - Signal P Cleavage Site => 10:11
MHLLCIVLLL-KWWLLL
>isotig00004_f6_8 - Signal P Cleavage Site => 11:12
MMHLLCIVLLL-KWWLLL
>isotig00004_f6_9 - Signal P Cleavage Site => 10:11
MHLLCIVLLL-KWWLLL
>isotig00009_f2_3 - Signal P Cleavage Site => 22:23
MLKCFSIIMGLILLLEIGGGCA-IYFYRAQIQAQFQKSLTDVTITDYRENADFQDLIDALQSGLSCCGVNSYEDWDNNIYFNCSGPANNPEALWCAFLLLYTGSSKRSSQHPVRLWSSFPRTTKYFPHKDLHHWLCGYVYNVD
>isotig00009_f3_9 - Signal P Cleavage Site => 16:17
MKTGIIIFISTVVVLP-ITLKPCGVPFSCCIPDQASGVANTQCGYGVRSPEQQNTFHTKIYTTGCADMFTMWINRYLYYIAGIAGVIVLVELFGFCFAHSLINDIKRQKARWAHR

我想要做的是将 sample.txt 拆分为条目(每 2 行)。然后我想将每个条目分成特定的部分,例如

>isotig00003_f6_8 - Signal P Cleavage Site => 11:12
MMHLLCIVLLL-KWWLLL

是由

definition -->        >isotig00003_f6_8 - Signal P Cleavage Site => 11:12
sequence (aaseq) -->  MMHLLCIVLLL-KWWLLL

然后我想将定义拆分为:

:id_start -->   >isotig00003_f6_8
:id_end -->     Signal P Cleavage Site => 11:12

并将序列(aaseq)拆分为:

:signalp -->    MMHLLCIVLLL
:seq_end -->    KWWLLL

我想要的是能够在其他方法中使用每个特定变量(:id_start,:id_end,:signalp,:seq_end)。

非常感谢所有帮助

4

1 回答 1

1

像这样的东西可能对你有用。这将生成一个包含哈希的数组;我希望这就是你所追求的。

lines = File.read('sample.txt').split "\n" # You can get your lines however you want.

# Step through the lines in pairs...
lines.each_slice(2).map do |definition, sequence|
  # Create a hash of the split and stripped data.
  Hash[[[:id_start, :id_end], definition.split('-').map(&:strip)].transpose].merge \
  Hash[[[:signalp, :seq_end], sequence.split('-').map(&:strip)].transpose]
end

如果您想让这些哈希值在较大哈希值中的某个键上可用,您可以这样做:

Hash[lines.each_slice(2).map do |definition, sequence|
       ['WHATEVER YOUR KEY IS GOES HERE', 
        Hash[[[:id_start, :id_end], definition.split('-').map(&:strip)].transpose].merge(
        Hash[[[:signalp, :seq_end], sequence.split('-').map(&:strip)].transpose]
       )]
     end]

(我不知道你的钥匙在这里,但你应该能够使用它。)

于 2013-11-01T22:55:45.793 回答