简体   繁体   中英

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.

Here is txt file where are my parameters which have to be placed in dict-> http://mign.pl/ver.txt

and dict should looks like this: dic = {"Version": 1.0, "Hires": False, "Temperature": 55, "Description": "some description"}

I have already used urllib2 to download content:

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 ):

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 )

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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM