[英]Checking last element of a string in a list
I have got some serial communications logs to analyze regarding time, so I record messages with timestamps in format YYYY-MM-DD HH:MM:SS.ffffff: So my file looks like this: 我有一些串行通信日志来分析时间,所以我用格式YYYY-MM-DD HH:MM:SS.ffffff记录时间戳的消息:所以我的文件看起来像这样:
YYYY-MM-DD HH:MM:SS.ffffff:
YYYY-MM-DD HH:MM:SS.ffffff:
few lines of bytes
几行字节
YYYY-MM-DD HH:MM:SS.ffffff:
YYYY-MM-DD HH:MM:SS.ffffff:
and so on...
等等...
I want to extract dates from my file so I could calculate times between messages 我想从我的文件中提取日期,以便我可以计算消息之间的时间
I want to operate on dates using datetime module, and for the beginning I wanted to get rid of the colons at the end of each date. 我想使用datetime模块操作日期,一开始我想在每个日期结束时去除冒号。 I have read my file and saved it in variable which is a list of strings, and each element is a line.
我已经读取了我的文件并将其保存在变量中,该变量是一个字符串列表,每个元素都是一行。 Now I want to create a second list of only dates, extracting only those lines that end with colons.
现在我想创建仅包含日期的第二个列表,仅提取以冒号结尾的那些行。
f=open("sniffinglog.txt","r")
lines=(f.readlines())
lines_number=len(lines)
i=0
dates=[]
while i<lines_number:
if lines[i].endswith(":"):
dates.append(lines[i])
i+=1
print (dates)
I checked that lines
is created correctly, however there are no elements appended to the list dates
. 我检查了
lines
是否正确创建,但是没有元素附加到列表dates
。 It remains empty. 它仍然是空的。 Is there something wrong with my
if
condition? 我的
if
条件有问题吗? Or is there another way of checking last character of a string if it is a list element? 或者是否有另一种方法来检查字符串的最后一个字符,如果它是一个列表元素?
This should work, if it doesn't then your lines probably don't end with :
. 这应该有用,如果没有,那么你的线可能不会以
:
。
with open("sniffinglog.txt", "r") as f:
content = f.readlines()
dates = []
for line in content:
if line.strip().endswith(":"):
dates.append(line.rstrip(":"))
print(dates)
You need to remove the new line from every line of the file. 您需要从文件的每一行删除新行。
Try to replace 尝试更换
lines=(f.readlines())
with 同
lines=[l.strip() for l in f.readlines()]
A better way to find the Timestamp in line 一种更好的方法来查找行中的时间戳
f=open("sniffinglog.txt","r")
lines=(f.readlines())
lines_number=len(lines)
i=0
dates=[]
while i<lines_number:
# Check if line is a timestamp.
if time.strptime(line[:19], '%Y-%m-%d %H:%M:%S'):
dates.append(lines[i])
i+=1
print (dates)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.