[英]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".我正在尝试编写一个代码,它从以“From”开头的行中提取时间码。 Example: "From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008" and then splits the timecode into hours and seconds.
示例:“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])
When I'm compiling my code - I'm getting the traceback (Attribute Error: 'list' object has no attribute 'split'
).当我编译我的代码时 - 我得到了回溯(属性错误:
'list' object has no attribute 'split'
)。 If I change my code to do the same for email:如果我更改我的代码以对 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!欢迎来到 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[5:6]
返回一个列表,但从字符串列表中获取第一项返回一个字符串。 ( words[1]
) (
words[1]
)
If you want to convert a list to a string, consider using "".join(mylist)
.如果要将列表转换为字符串,请考虑使用
"".join(mylist)
。 Check out this article on W3Schools for more info on how to use join.查看这篇关于 W3Schools的文章,了解有关如何使用加入的更多信息。
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.