poem = '''\
me:hello dear
me:hyyy
asha:edaaaa
'''
f=open('poem.txt','r')
arr=[]
arr1=[]
varr=[]
darr=[]
i=0
j=1
for line in f.read().split('\n'):
arr.append(line)
i+=1
f.close()
#print arr[0]
#print arr[1]
#print arr[2]
text=arr[0].split(':')
#print text
line=text[0]
#print line
arr1.append(text[1])
for i in range(1,len(arr)):
text=arr[i].split(':')
if(line==text[0]):
#print text[1]
arr1.append(text[1])
else:
if(j==1):
j+=1
varr[j]=text[0] # this is not working
darr[j]=text[1]
print len(varr)
f.close()
print arr1
views:
80answers:
2
A:
You are attempting to assign to varr[2]
, but varr
is an empty list, so you would get an index error
There are a number of ways to fix this code, but it's not clear to me what the code is supposed to do
Nosklo's answer seemed reasonable to me, until I thought about it some more. I am not sure there is much point grouping the lines by the name since it means that the overall structure of the file is lost.
Here is how to simply parse the file into a list
which you can manipulate later
result = []
with open('poem.txt') as f:
for line in f:
result.append(line.partition(':')[::2])
print result
gnibbler
2010-09-03 12:18:44
@gnibbler: I _suspect_ (not sure) that the OP is trying to read lines and collect them into different arrays based on a part of the line (username, I presume).
Manoj Govindan
2010-09-03 12:23:23
@Manoj, you may be right, and it looks like nosklo agrees. I am not sure why the first line is treated specially or what the various arr, varr, darr represent though.
gnibbler
2010-09-03 12:30:30
+5
A:
CRYSTAL BALL MODE ON
from collections import defaultdict
result = defaultdict(list)
with open('chat.log') as f:
for line in f:
nick, msg = line.split(':', 1)
result[nick].append(msg)
print result
nosklo
2010-09-03 12:25:06
You didn't turn crystal ball mode off at the end! Who knows what unresolved references you may be leaving around!
Daniel Roseman
2010-09-03 12:28:39
+1 for use of crystal ball. Beyond that, my comments have nothing to do with the answer and everything to do with not being clear what problem @anu wants this to solve. I'm not sure indexing messages by nick really gives you anything. For one, the order of the messages, including the order relative to messages by other nicks, is probably important. I can't see the resulting structure from this code being anything useful.
asveikau
2010-09-03 19:40:57