2

I'm trying to write a code, which extracts timecodes from lines that start with "From". Example: "From [email protected] Sat Jan 5 09:14:16 2008" and then splits the timecode into hours and seconds.

fhand = open('mbox-short.txt')

for line in fhand :
    line = line.rstrip()
    if not line.startswith('From') : continue
    words = line.split()
    time = words[5:6]
    hrs = time.split(':')
    print(hrs[1])
    print(hrs[2])

When I'm compiling my code - I'm getting the traceback (Attribute Error: 'list' object has no attribute 'split'). If I change my code to do the same for email:

fhand = open('mbox-short.txt')

for line in fhand :
    line = line.rstrip()
    if not line.startswith('From') : continue
    words = line.split()
    time = words[1]
    hrs = time.split('@')
    print(hrs[1])

everything is alright - the program works properly (splits emails into logins and domains). What's wrong with the first code?

1
  • 2
    Slicing words[5:6] returns a list even if there is only one thing in it Commented Jul 14, 2020 at 15:53

3 Answers 3

2

Welcome to SO!

Firstly, lists have no property called 'split'. Strings do, though!

This means that in your first example, you're trying to split a list, but in the second example, you're splitting a string. This is because doing words[5:6] returns a list, but getting the first item from a list of strings returns a string. (words[1])

If you want to convert a list to a string, consider using "".join(mylist). Check out this article on W3Schools for more info on how to use join.

Sign up to request clarification or add additional context in comments.

Comments

1

As a previous person already said, you can't split list, the reason the fist code works is because you are splitting one element of the list, which is a string, what you could do iterate in each element of the time array to print all of them

fhand = open('mbox-short.txt')

for line in fhand :
    line = line.rstrip()
    if not line.startswith('From') : continue
    words = line.split()
    time = words[5:6]
    for elem in time:
        hrs = time.split(':')
        print(hrs[1])
        print(hrs[2])

Comments

1

Try this:

fhand = open('mbox-short.txt')

for line in fhand :
    line = line.rstrip()
    if not line.startswith('From') : continue
    words = line.split()
    time = words[5]
    hrs = time.split(':')
    print(hrs[1])
    print(hrs[2])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.