简体   繁体   中英

Attribute Error in Python: 'list' object has no attribute 'split'

I'm trying to write a code, which extracts timecodes from lines that start with "From". Example: "From stephen.marquard@uct.ac.za 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?

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.

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])

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])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM