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
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
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
精彩评论