I have a file that has a bunch of numbers, but there are headings that are keeping me from doing much. The file looks like this:
x:
1 2 3 4
f:
5 6 7 8
h:
9 10 11 12 13
so I have this program which i believe will help me access the numbers but I get an error message about it.
filename = input('file: ')
f = open(filename, 'r')
output=[]
w, h = map(int,lines.split())
x=[]
for i, line in enumerate(f):
if i == h:
break
x.append(map(int,line.split()[:w]))
output.append(x)
So i tried striping the headers, but I get an error message about it being a string and such.
filename = input('file: ')
f = open(filename, 'r')
output=[]
func = f.readline()
lines = func.strip('x').strip('f').strip('h').split()
w, h = map(int,lines.split())
x=[]
for i, line in enumerate(f):
if i == h:
break
x.append(map(int,line.split()[:w]))
output.append(x)
any advice?
If the heading are distinct, parse as follows?
x -> [1,2,3,4]
f -> [5,6,7,8]
h -> [9,10,11,12,13]
Is this what you are after?
Just read file normally and strip all characters? Quick code, haven't tested but you should be able to easily adapt.
import re
with open (filename, "r") as myfile:
for line in myfile.readlines():
data =re.sub(r"\D", "", line)
parsefile.py:
import re
with open('file.txt', 'rU') as data:
mydict = {}
for line in data:
varname = re.search('(\w+):', line)
if varname:
mydict[varname.group(1)] = [int(num) for num in data.next().split()]
print 'x = ', mydict['x']
print 'f = ', mydict['f']
print 'h = ', mydict['h']
file.txt:
x:
1 2 3 4
f:
5 6 7 8
h:
9 10 11 12 13
output:
(parsedigitsheaders)macbook:parsedigitsheaders joeyoung$ python parsefile.py
x = [1, 2, 3, 4]
f = [5, 6, 7, 8]
h = [9, 10, 11, 12, 13]
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.