简体   繁体   中英

Python: How can I read a file with format of a list?

I have the below file (g)..

-verifiziert.com | [1401832800]
00.pm | [1418511600, 1418598000, 1418943600]
00.re | [1410213600, 1417906800, 1418425200, 1419116400, 1418770800, 1417993200]
-verifizierungen.ne | [1401832800]
0.mk | [1414796400, 1415919600, 1417129200, 1416783600]

and I want to put it into a dictionary of d[domains]=numbers. and for each number in the list, I want an integer since it is a string currently.

I am using this code :

d = defaultdict(list)
for line in g:
    line = line.strip('\n')
    domain, bl_dates= line.split('|')
    bl_dates = [int(i) for i in bl_dates]
    d[domain].append(bl_dates)

but I am getting this error, seems like the list is not recognized as a list :

Traceback (most recent call last):
  File "test.py", line 12, in <module>
    bl_dates = [int(i) for i in bl_dates]
ValueError: invalid literal for int() with base 10: '['

Can anybody help me with this?

regex is your friend here:

import re

line = "00.pm | [1418511600, 1418598000, 1418943600]"
domain, bl_dates = re.split('\s+\|\s+', line)
res = [int(i) for i in re.findall('\d+', bl_dates)]
print res #  prints [1418511600, 1418598000, 1418943600]

This sort of thing should work:

import json
d = defaultdict(list)
for line in g:
    domain, list = line.split('|')
    d[domain.strip()] = json.loads(list)

At the end, d looks like this:

{'00.re': [1410213600, 1417906800, 1418425200, 1419116400, 1418770800, 1417993200],
 '-verifizierungen.ne': [1401832800],
 '0.mk': [1414796400, 1415919600, 1417129200, 1416783600],
 '-verifiziert.com': [1401832800],
 '00.pm': [1418511600, 1418598000, 1418943600],
 }

you can use ast.literal_eval :

>>> import ast
>>> ast.literal_eval("00.pm | [1418511600, 1418598000, 1418943600]".split("|")[1].strip())
[1418511600, 1418598000, 1418943600]

so ur code will be like this:

import ast
my_dict = {}
with open('your_file') as f:
     for x in f:
         key, value = x.strip().split("|")
         my_dict[key.strip()] = ats.literal_eval(value.strip())

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