我有一个代码试图从桌面获取数据,然后解析到网页,翻译并粘贴翻译为输出
import urllib,urllib2
with open('/path to the data/data.txt') as f:
lines = f.read().splitlines()
with open('/path to the output/output.txt') as ff:
url = 'http://www.uniprot.org/mapping/'
print "From To"
for genename_id in lines:
params = {
'from':'ACC+ID',
'to':'GENENAME',
'format':'tab',
'query':genename_id
}
data = urllib.urlencode(params)
request = urllib2.Request(url, data)
contact = "" # Please set your email address here.
request.add_header('User-Agent', 'Python %s' % contact)
response = urllib2.urlopen(request)
page = response.read(200000)
ff.write(page.splitlines()[1])
data.txt在
之下G5E8R3
Q99MR6-3
D3YVD3
G3UZM2
Q1MWP8
D3Z2K3
Q8BZM2
P09103
Q9JJG0-3
Q9R0Q6
Q3UY11
Q8C3Z4
Q3UVN6
Q80U36
Q9R1A1
我试图做两件事
1-我希望能够转换数据,如果它不存在,我希望从一个不存在的空间中获得一个空的空间
这样的欲望输出
From To
G5E8R3 Pcx
Q99MR6-3
D3YVD3 Eno2
G3UZM2 Rhoj
Q1MWP8 Ehd4
D3Z2K3 Actg2
Q8BZM2 Anks1b
P09103 P4hb
Q9JJG0-3
Q9R0Q6 Arpc1a
Q3UY11 Scamp1
Q8C3Z4 Prkar1a
Q3UVN6 Abi2
Q80U36 Dync1h1
Q9R1A1
答案 0 :(得分:0)
您的问题与撰写output.txt
write
权限打开它,这将导致IOError
例外。总之,请考虑下一个代码:
import urllib
import urllib2
with open('/path/to/data.txt') as f:
lines = f.read().splitlines()
with open('/path/to/output.txt', 'w') as ff:
url = 'http://www.uniprot.org/mapping/'
ff.write("From\tTo\n")
for genename_id in lines:
params = {
'from': 'ACC+ID',
'to': 'GENENAME',
'format': 'tab',
'query': genename_id
}
data = urllib.urlencode(params)
request = urllib2.Request(url, data)
contact = "some@email.addrs"
request.add_header('User-Agent', 'Python %s' % contact)
response = urllib2.urlopen(request)
page = response.read()
ff.write('%s\n' % (page.splitlines()[1] if len(page.splitlines()) > 1 else genename_id))
注意:
'w'
作为open
文件的output.txt
函数的第二个参数,因此我将拥有写入权限。阅读open
函数here。response.read
。print "From To"
更改为ff.write("From\tTo\n")
,因此它会显示在output.txt
文件中。