【发布时间】:2016-11-30 20:38:31
【问题描述】:
我是编程新手,我需要帮助找出用户输入在 txt 文件中出现的次数。我目前拥有的代码是:
myfile = open("WorldSeriesWinners.txt")
count = 0
team = input("Enter in the team name that won the world series: ")
line = myfile.readline()
myfile.readline()
while team in line:
count += 1
myfile.readline()
print("The", team, "won the world series", count, "times")
myfile.close()
我从中得到的输出是:
Enter in the team name that won the world series: New York Yankees
The New York Yankees won the world series 0 times
如何让它显示特定球队获胜的次数?提前致谢。
【问题讨论】:
-
你能贴几行文本文件吗?
-
如果该团队在排队,那么您自己就有一个无限循环,您可能应该在线和团队使用
lower()或upper(),以便案例匹配 -
你能不能在行中使用
split(),然后在结果列表中使用count()? -
@ElliotRoberts 在使用
count()之前无需split,因为它适用于字符串