我正在试着写一段代码,从以" 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])一切都很好-程序工作正常(将电子邮件分成登录和域名)。第一个代码有什么问题?
发布于 2020-07-15 00:06:34
欢迎来到SO!
首先,列表没有叫做“split”的属性。不过,字符串可以!
这意味着在第一个示例中,您试图拆分一个列表,但在第二个示例中,您正在拆分一个字符串。这是因为执行words[5:6]会返回一个列表,而从字符串列表中获取第一个项目则会返回一个字符串。(words[1])
如果要将列表转换为字符串,请考虑使用"".join(mylist)。有关如何使用join的更多信息,请查看this article on W3Schools。
发布于 2020-07-15 02:25:52
正如前面的人所说的,你不能拆分列表,第一个代码之所以有效,是因为你拆分了列表的一个元素,这是一个字符串,你可以在时间数组的每个元素中迭代以打印所有元素
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])发布于 2020-07-15 21:38:00
试试这个:
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])https://stackoverflow.com/questions/62899058
复制相似问题