[英]fetch data from .txt web file (as key,value set) into dictionary
I need to download content of .txt file from web, separate each key,value set and insert them into dictionary. 我需要从Web下载.txt文件的内容,分离每个键,值集并将它们插入字典中。
Here is txt file where are my parameters which have to be placed in dict-> http://mign.pl/ver.txt 这是txt文件,我的参数必须放在dict-> http://mign.pl/ver.txt中
and dict should looks like this: dic = {"Version": 1.0, "Hires": False, "Temperature": 55, "Description": "some description"}
并且dict应该看起来像这样:
dic = {"Version": 1.0, "Hires": False, "Temperature": 55, "Description": "some description"}
I have already used urllib2 to download content: 我已经使用urllib2下载内容:
import urllib.request as urllib2
url = urllib2.urlopen('http://www.mign.pl/ver.txt')
What next? 接下来是什么?
You can use built-in configparser
module to parse the values ( doc ): 您可以使用内置的
configparser
模块来解析值( doc ):
import configparser
import urllib.request as urllib2
data = urllib2.urlopen('http://www.mign.pl/ver.txt')
c = configparser.ConfigParser()
c.read_string('[root]\n' + data.read().decode('utf-8'))
print({k:v for k, v in zip(c['root'], c['root'].values())})
Prints: 印刷品:
{'version': '1.0', 'hires': 'False', 'temperature': '55', 'description': 'Some description'}
Or just work with connfigparser directly (eg print(c['root']['version'])
will print 1.0
) 或者直接使用connfigparser(例如,
print(c['root']['version'])
将输出1.0
)
try this : 尝试这个 :
import urllib.request as urllib2
url = urllib2.urlopen('http://www.mign.pl/ver.txt')
d1={}
x=url.read().decode("utf-8")
d=x.split("\n")
for i in d:
z=i.split("=")
d1[str(z[0])]=z[1]
print(d1)
output: 输出:
{'Version ': ' 1.0', 'Hires ': ' False', 'Description ': ' Some description', 'Temperature ': ' 55'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.