nik nik - 3 months ago 8
Ruby Question

how to amend a code to get query from external and save result to external

I have a code which looks like this

require 'net/http'

base = 'www.uniprot.org'
tool = 'mapping'
params = {
'from' => 'ACC+ID', 'to' => 'P_ENTREZGENEID', 'format' => 'tab',
'query' => 'A0A0K3AVS5 A0A0K3AVV4 A0A0K3AW32 A0A0K3AWP0'
}

http = Net::HTTP.new base
$stderr.puts "Submitting...\n";
response = http.request_post '/' + tool + '/',
params.keys.map {|key| key + '=' + params[key]}.join('&')

loc = nil
while response.code == '302'
loc = response['Location']
response = http.request_get loc
end

while loc
wait = response['Retry-After'] or break
$stderr.puts "Waiting (#{wait})...\n";
sleep wait.to_i
response = http.request_get loc
end

response.value # raises http error if not 2xx
puts response.body


which gives me what I need. however, I have two questions

1- How to load a query list instead I parse it into the code ? lets say I save a txt file with all the query i want to the desktop of a mac

2- How to export the output ?

If I have

B2D6P1
G5EC52
B2FDA8-2
B2MZB1
B3CJ34
B3CKG1
B3GWA1


what @tadman showed gives me the answer
however, I have the following

B2D6P1
G5EC52;B2D6P4
B2FDA8-2;B2FDA8
B2MZB1;P18834
B3CJ34
B3CKG1
B3GWA1;Q8I7K5


and the answer is like below

B2D6P1 rmd-2
G5EC52 tlf-1
B2D6P4 tlf-1
B2FDA8 smc-3
B2MZB1 col-14
P18834 col-14
B3CJ34 gcn-1
B3CKG1 urm-1
B3GWA1 nono-1
Q8I7K5 nono-1


what I want is that if I have two entries in each row (separated with ;) leading to the similar output , it gives me only one , otherwise give me as many as they have for example in above example , my desire output is

B2D6P1 rmd-2
G5EC52;B2D6P4 tlf-1
B2FDA8-2;B2FDA8 smc-3
B2MZB1;P18834 col-14
B3CJ34 gcn-1
B3CKG1 urm-1
B3GWA1;Q8I7K5 nono-1


is this possible ?

Answer

Reading query data:

query = File.readlines('ids.txt').map(&:chomp).join(' ')

That way you can have them on separate lines, easier to edit, and they're space separated when submitted.

That makes your params look like:

params = {
  'query' => query,
  ...
}

Writing data:

File.open('output.txt', 'w') do |f|
  f.write(response.body)
end

That's all there is to it. If it's a string, or can be converted to a string, you can write it to a file.