开发者

to parse chat conversations stored in a file [closed]

开发者_运维问答 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.
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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜