-1

我的文本文件数据如下所示:(蛋白质-蛋白质相互作用数据)

转录因子蛋白

Myc Rilpl1

Mycn Rilpl1

Mycn "Wdhd1,Socs4"

Sox2 Rilpl1

Sox2 "Wdhd1,Socs4"

Nanog“Wdhd1,Socs4”

我希望它看起来像这样:(要查看每种蛋白质与多少个转录因子相互作用)

蛋白质转录因子

Rilpl1 Myc、Mycn、Sox2

Wdhd1 Mycn、Sox2、Nanog

Socs4 Mycn、Sox2、Nanog

使用我的代码后,我得到的是:(我怎样才能摆脱“”并将两个蛋白质分离到新行)

蛋白质转录因子

Rilpl1 Myc、Mycn、Sox2

"Wdhd1,Socs4" Mycn, Nanog, Sox2

这是我的代码:

input_file = ARGV[0]
hash = {}
File.readlines(input_file, "\r").each do |line|
  transcription_factor, protein = line.chomp.split("\t")

  if hash.has_key? protein
    hash[protein] << transcription_factor
  else
    hash[protein] = [transcription_factor]
  end
end

hash.each do |key, value|
  if value.count > 2
    string = value.join(', ')
    puts "#{key}\t#{string}"
  end
end
4

1 回答 1

1

这是解决问题的快速方法:

...
transcription_factor, proteins = line.chomp.split("\t")
proteins.to_s.gsub(/"/,'').split(',').each do |protein|
  if hash.has_key? protein
    hash[protein] << transcription_factor
  else
    hash[protein] = [transcription_factor]
  end
end
...

上面的代码片段基本上会从蛋白质中删除引号(如果有的话),然后对于找到的每个蛋白质,它都会执行您已经编写的操作。

此外,如果您想消除如果您可以像这样定义散列:

hash = Hash.new {|hash,key| hash[key]= []}

这意味着对于每个新key的它将返回一个新的数组。所以现在你可以跳过if并写

hash[protein] << transcription_factor
于 2014-02-05T14:34:48.933 回答