出于某种原因,我无法返回用户输入在文章中出现的次数。这是我的代码
infile = open ("the path to the file...blah blah")
count = 0
for line in infile:
user = input("please enter a search term or click x to exist: " )
if user in line:
count = count + 1
print("your input appears",count "times")
else:
print("invalid")
infile.close()
答案 0 :(得分:0)
由于多种原因,您的上述计划有误。首先,正如评论中提到的那样,您必须在打印count
之后使用逗号或将其设为str(count)
并在打印时添加到字符串中。从逻辑上讲,您的程序错误,因为您的计数变量仅在每行打印输出之前附加一次。您需要的是在总计数后打印它。
尝试这个简单的解决方案。
infile = open ("your_file")
count = 0
lines = infile.readlines()
lines = [line.strip().split() for line in lines]
user = input("please enter a search term or click x to exist: " )
for line in lines:
if user in line:
count += line.count(user)
print("your input appears " + str(count) + " times")
infile.close()
这适用于您的场景。