我想检查一个字符串是否在文本文件中。如果是,执行x。如果不是,执行y。然而,由于某种原因,这段代码总是返回True。有人能看出哪里不对吗?

def check():
    datafile = file('example.txt')
    found = False
    for line in datafile:
        if blabla in line:
            found = True
            break

check()
if True:
    print "true"
else:
    print "false"

if True:
    print "true"

这种情况经常发生,因为True总是True。

你想要这样的东西:

if check():
    print "true"
else:
    print "false"

好运!


正如Jeffrey所说,您不是在检查check()的值。此外,check()函数没有返回任何东西。注意区别:

def check():
    with open('example.txt') as f:
        datafile = f.readlines()
    found = False  # This isn't really necessary
    for line in datafile:
        if blabla in line:
            # found = True # Not necessary
            return True
    return False  # Because you finished the search without finding

然后你可以测试check()的输出:

if check():
    print('True')
else:
    print('False')

check函数应该返回找到的布尔值,并使用它来确定要打印的内容。

def check():
        datafile = file('example.txt')
        found = False
        for line in datafile:
            if blabla in line:
                found = True
                break

        return found

found = check()
if found:
    print "true"
else:
    print "false"

第二部分也可以压缩为:

if check():
    print "true"
else:
    print "false"

found = False

def check():
    datafile = file('example.txt')
    for line in datafile:
        if blabla in line:
            found = True
            break
    return found

if check():
    print "true"
else:
    print "false"

两个问题:

你的函数没有返回任何东西;不显式返回任何内容的函数返回None(这是假的) True始终为True—您不是在检查函数的结果

.

def check(fname, txt):
    with open(fname) as dataf:
        return any(txt in line for line in dataf)

if check('example.txt', 'blabla'):
    print "true"
else:
    print "false"

为什么你总是得到True的原因已经给出了,所以我只提供另一个建议:

如果你的文件不是很大,你可以把它读入一个字符串,然后使用它(比逐行读取和检查更容易,通常也更快):

with open('example.txt') as f:
    if 'blabla' in f.read():
        print("true")

另一个技巧:你可以通过使用mmap.mmap()来创建一个“类似字符串”的对象,使用底层文件(而不是在内存中读取整个文件)来缓解可能的内存问题:

import mmap

with open('example.txt') as f:
    s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    if s.find('blabla') != -1:
        print('true')

注意:在python 3中,mmap的行为更像bytearray对象而不是字符串,所以你用find()查找的子序列必须是一个bytes对象而不是字符串,例如。s.find (b 'blabla”):

#!/usr/bin/env python3
import mmap

with open('example.txt', 'rb', 0) as file, \
     mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
    if s.find(b'blabla') != -1:
        print('true')

你也可以在mmap上使用正则表达式,例如,不区分大小写的搜索:if re.search(br'(?i)blabla', s):


这里有另一种可能回答你的问题的方法,使用find函数,它给你一个文字数值,告诉你某物真正在哪里

open('file', 'r').read().find('')

在find中写下你想要找到的单词 'file'代表你的文件名


如何搜索文件中的文本并返回在其中找到的字的文件路径 (Какискатьчастьтекставфайлеивозвращятьпутькфайлувкоторомэтословонайдено)

import os
import re

class Searcher:
    def __init__(self, path, query):
        self.path   = path

        if self.path[-1] != '/':
            self.path += '/'

        self.path = self.path.replace('/', '\\')
        self.query  = query
        self.searched = {}

    def find(self):
        for root, dirs, files in os.walk( self.path ):
            for file in files:
                if re.match(r'.*?\.txt$', file) is not None:
                    if root[-1] != '\\':
                        root += '\\'           
                    f = open(root + file, 'rt')
                    txt = f.read()
                    f.close()

                    count = len( re.findall( self.query, txt ) )
                    if count > 0:
                        self.searched[root + file] = count

    def getResults(self):
        return self.searched

在Main ()

# -*- coding: UTF-8 -*-

import sys
from search import Searcher

path = 'c:\\temp\\'
search = 'search string'


if __name__ == '__main__':

    if len(sys.argv) == 3:
        # создаем объект поисковика и передаем ему аргументы
        Search = Searcher(sys.argv[1], sys.argv[2])
    else:
        Search = Searcher(path, search)

    # начать поиск
    Search.find()

    # получаем результат
    results = Search.getResults()

    # выводим результат
    print 'Found ', len(results), ' files:'

    for file, count in results.items():
        print 'File: ', file, ' Found entries:' , count

我为此做了一个小函数。它在输入文件中搜索单词,然后将其添加到输出文件中。

def searcher(outf, inf, string):
    with open(outf, 'a') as f1:
        if string in open(inf).read():
            f1.write(string)

Outf是输出文件 Inf是输入文件 String当然是您希望找到并添加到outf的所需字符串。


如果用户想在给定的文本文件中搜索单词。

 fopen = open('logfile.txt',mode='r+')

  fread = fopen.readlines()

  x = input("Enter the search string: ")

  for line in fread:

      if x in line:

          print(line)

found = False
def check():
datafile = file('example.txt')
for line in datafile:
    if "blabla" in line:
        found = True
        break
return found

if check():
    print "found"
else:
    print "not found"

这是另一个。获取绝对文件路径和给定字符串并将其传递给word_find(),在enumerate()方法中对给定文件使用readlines()方法,该方法在逐行遍历时给出可迭代计数,最终为您提供具有匹配字符串的行,加上给定的行号。欢呼。

  def word_find(file, word):
    with open(file, 'r') as target_file:
        for num, line in enumerate(target_file.readlines(), 1):
            if str(word) in line:
                print(f'<Line {num}> {line}')
            else:
                print(f'> {word} not found.')


  if __name__ == '__main__':
      file_to_process = '/path/to/file'
      string_to_find = input()
      word_find(file_to_process, string_to_find)

"found"需要在函数中作为全局变量创建,因为"if else"语句不在函数中。您也不需要使用“break”来中断循环代码。 下面的方法可以确定文本文件是否有所需的字符串。

with open('text_text.txt') as f:
    datafile = f.readlines()


def check():
    global found
    found = False
    for line in datafile:
        if 'the' in line:
            found = True


check()

if found == True:
    print("True")
else:
    print("False")