繁体   English   中英

Python 中的属性错误:“列表”object 没有属性“拆分”

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

我正在尝试编写一个代码,它从以“From”开头的行中提取时间码。 示例:“From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008”,然后将时间码拆分为小时和秒。

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

当我编译我的代码时 - 我得到了回溯(属性错误: 'list' object has no attribute 'split' )。 如果我更改我的代码以对 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])

一切正常 - 程序正常运行(将电子邮件拆分为登录名和域)。 第一个代码有什么问题?

欢迎来到 SO!

首先,列表没有称为“拆分”的属性。 不过,字符串可以!

这意味着在您的第一个示例中,您尝试拆分列表,但在第二个示例中,您正在拆分字符串。 这是因为执行words[5:6]返回一个列表,但从字符串列表中获取第一项返回一个字符串。 words[1]

如果要将列表转换为字符串,请考虑使用"".join(mylist) 查看这篇关于 W3Schools的文章,了解有关如何使用加入的更多信息。

正如前人所说,您不能拆分列表,第一个代码起作用的原因是因为您要拆分列表的一个元素,这是一个字符串,您可以在时间数组的每个元素中迭代以打印他们全部

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

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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