【问题标题】:Attribute Error in Python: 'list' object has no attribute 'split'Python中的属性错误:'list'对象没有属性'split'
【发布时间】:2020-07-14 15:52:30
【问题描述】:

我正在尝试编写一个代码,它从以“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')。如果我更改我的代码以对电子邮件执行相同的操作:

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

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

【问题讨论】:

  • 切片words[5:6]会返回一个列表,即使里面只有一件事

标签: python list split attributes traceback


【解决方案1】:

欢迎来到 SO!

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

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

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

【讨论】:

    【解决方案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:6]
        for elem in time:
            hrs = time.split(':')
            print(hrs[1])
            print(hrs[2])
    

    【讨论】:

      【解决方案3】:

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-29
        • 2020-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多