[英]python split list in txt
文本文件如下所示:
helen:9,5,7
john:5,4,3
beta:9,9,9
我是python的新手,如何拆分呢? 我不断收到属性错误:
AttributeError:“列表”对象没有属性“分割”
def readText(group):
snap = []
with open(group+'.txt','r') as text:
for line in text:
name = line.split(':')[0]
score = max(line.split(':')[1].split(',').split()[0])
snap.append([name,score])
export = sorted(snap, key=lambda x:x[0])
print ('Student highest score, in alphabetical order')
for L in export:
print (L[0]+':'+L[1])
if __name__ == '__main__':
scores = [0,0,0]
readText(group)
拆分是str的功能,如您在此处看到的(搜索str.split) https://docs.python.org/2/library/stdtypes.html
该行的第二个拆分
score = max(line.split(':')[1].split(',').split()[0])
将字符串“ 9,5,7”拆分为列表['9','5','7']。 再次调用split会给出您看到的错误。
您希望分数是第二个拆分中列表的max()。
另外,请确保您说明在空白行上发生的情况。 如果有空白行,您致电
line.split(':')[1]
会有麻烦。
split() #returns a list, so you can't call split().split()
score = max(line.split(':')[1].split(',').split()[0])
您可以在拆分之前删除前线
name = line.split(':')[0]
score = max( s[-(s.find(":")):].split(",") )
snap.append([name,score])
您可以将for循环的内容更改为:
name, scores = line.split(':',2)
score = max(scores.split(','))
snap.append([name,score])
我会为此使用带有组的正则表达式。
import re
def readText(group):
snap = []
with open(group+'.txt','r') as text:
for line in text:
matches = re.match(pattern="^(\w+):([\d\,\.]+)", string=line, flags=re.IGNORECASE)
if matches is not None:
print(matches.group(1))
print(matches.group(2))
max_score = max([float(x) for x in str.split(matches.group(2), sep=',')])
print(max_score)
if __name__ == '__main__':
readText('data')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.