我正在尝试编写的代码应该读取文本文件,并检查“EASTS”或“WESTS”得分了多少次,我可以使用 find 和“EASTS”或“WESTS”来获取数字。
但我不是得到出现的次数,而是得到它在每行中存在的次数。
So:
1
1
1
1
(我不知道为什么在属于西方的 1 之前有空格)
正文如下:
EASTS versus WESTS
EASTS have scored 25:13
WESTS have scored 26:38
WESTS have scored 40:23
WESTS have scored 42:01
这是我的代码,我做错了什么?
name = "scores.txt"
with open(name) as f:
ff = f.readlines()[1:]
for line in ff:
words = line.split()
a = words.count('EASTS')
b = words.count('WESTS')
a_ = str(a)
b_ = str(b)
eas = a_.strip('0')
wes = b_.strip('0')
print(eas, wes)
结果应该是这样的
WESTS 3
EASTS 1
有人可以帮忙吗?先感谢您!
初始化变量(wests
, easts
) 为 0。在循环中加 1。打印结果。
import itertools
team1, team2 = 'WESTS', 'EASTS'
count1, count2 = 0, 0
with open('scores.txt') as f:
for line in itertools.islice(f, 1, None):
if line.startswith(team1):
count1 += 1
else:
count2 += 1
print(team1, count1)
print(team2, count2)
在运行时获取团队名称
with open('scores.txt') as f:
team1, _, team2 = next(f).split()
count1, count2 = 0, 0
for line in f:
if line.startswith(team1):
count1 += 1
else:
count2 += 1
print(team1, count1)
print(team2, count2)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)