Python 有没有办法在文本文件中多次拆分一行?
我有一个名为log.txt的文本文件Python 有没有办法在文本文件中多次拆分一行?,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我有一个名为log.txt的文本文件 1.a Receiver Type : REC-1 Satellite System : GPS Serial Number : A123 1.b Receiver Type : REC-2 Satellite System : GPS Serial Number : B456 1.c Re
1.a Receiver Type : REC-1
Satellite System : GPS
Serial Number : A123
1.b Receiver Type : REC-2
Satellite System : GPS
Serial Number : B456
1.c Receiver Type : REC-3
Satellite System : GPS
Serial Number : C789
我可以只打印“卫星系统”和“序列号”的冒号“:”后的值。但是我不能对“Receiver Type”做同样的处理,因为“Receiver Type”行前面有3个字符。我能做到吗?有没有办法将一行拆分多次?对Python来说是完全陌生的。因此,任何能帮助我实现目标的事情都将不胜感激。谢谢
这是我目前拥有的代码,它只在冒号后打印“卫星系统”和“序列号”的值
with open('log.txt', 'r') as Log:
for line in Log:
if line.split(':')[0].strip() == 'Satellite System':
sat_sys = line.split(':')[1].strip()
print sat_sys
if line.split(':')[0].strip() == 'Serial Number':
ser_num = line.split(':')[1].strip()
print ser_num
是.strip()把事情搞砸了,而不是.split(“:”),但您可以这样做:
with open('log.txt', 'r') as Log:
for line in Log:
header = line.split(':')[0]
if 'Satellite System' in header:
sat_sys = line.split(':')[1].strip()
print sat_sys
elif 'Serial Number' in header:
ser_num = line.split(':')[1].strip()
print ser_num
elif 'Receiver Type' in header:
rec_typ = line.split(':')[1].strip()
print rec_typ
是.strip()把事情搞砸了,而不是.split(“:”),但您可以这样做:
with open('log.txt', 'r') as Log:
for line in Log:
header = line.split(':')[0]
if 'Satellite System' in header:
sat_sys = line.split(':')[1].strip()
print sat_sys
elif 'Serial Number' in header:
ser_num = line.split(':')[1].strip()
print ser_num
elif 'Receiver Type' in header:
rec_typ = line.split(':')[1].strip()
print rec_typ
你可以做如果行中有“接收器类型”
做你的事,行中有“卫星系统”
做另一件事行中有“序列号”`elif>做另一件事否则默认的事。这不管用吗?你可以做如果行中的“接收器类型”做你的事,行中的elif“卫星系统”做另一件事行中的`elif“序列号”做另一件事否则默认的事。这不管用吗?太好了:)。谢谢你,我会仔细考虑你的回答。完美:)。谢谢你,我会仔细考虑你的回答。