Python 在整个文章中搜索用户输入

Python 在整个文章中搜索用户输入,python,for-loop,Python,For Loop,由于某些原因,我无法返回用户输入在文章中出现的次数。这是我的密码 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("

由于某些原因,我无法返回用户输入在文章中出现的次数。这是我的密码

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()

你上面的程序有很多错误。首先,正如评论中提到的,打印时必须在
count
后加一个逗号,或者将其设置为
str(count)
,并在打印时添加到字符串中。从逻辑上讲,您的程序是错误的,因为在打印每行输出之前,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()

这应该适用于您的场景。

您是否遇到错误?尝试在打印语句中的
count
后加逗号。是否应该在循环外部定义用户?错误如下:请输入搜索词或单击x以存在:请输入搜索词或单击x以存在:谢谢您的评论。现在可以了。然而,我仍然想知道下面的代码是什么意思?lines=[line.strip().split()for lines in lines]以及为什么它是“count+=line.count(user)”而不是“count+=count+1”当文件第一次读入lines变量时,它会变成一个列表,其中文件的每一行都是它的元素。整个句子成为一个元素。
lines=[line.strip().split()for lines in lines]
所做的是,它迭代读取每一行,从行尾去除空白字符,并将每个句子拆分为一个单词列表,并用这个新创建的单词列表替换行列表中的原始句子。
count+=line.count(user)
所做的是计算给定单词在每个单词列表中出现的次数,并将其添加到总数中。