如何在文本文件中搜索字符串?

时间:2011-02-09 00:09:48

标签: python

我想检查字符串是否在文本文件中。如果是,请执行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"

12 个答案:

答案 0 :(得分:311)

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

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

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

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

import mmap

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

注意:在python 3中,mmaps的行为类似于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):

答案 1 :(得分:25)

正如Jeffrey Said所说,你没有检查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')

答案 2 :(得分:16)

这是另一种可能使用find函数回答你问题的方法,该函数为你提供了真正意义上的文字数值

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

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

答案 3 :(得分:12)

if True:
    print "true"

这总是发生,因为True始终为True。

你想要这样的东西:

if check():
    print "true"
else:
    print "false"
祝你好运!

答案 4 :(得分:4)

您的check函数应返回found布尔值并使用它来确定要打印的内容。

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"

答案 5 :(得分:4)

我为此目的做了一点功能。它在输入文件中搜索一个单词,然后将其添加到输出文件中。

def searcher(outf, inf, string):
    with open(outf, 'a') as f1:
        if string in open(inf).read():
            f1.write(string)
  • outf是输出文件
  • inf是输入文件
  • string当然是您希望找到并添加到outf的所需字符串。

答案 6 :(得分:2)

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

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

答案 7 :(得分:1)

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"

答案 8 :(得分:1)

两个问题:

  1. 您的功能不会返回任何内容;一个没有显式返回任何东西的函数返回None(这是假的)

  2. True始终为True - 您没有检查函数的结果

  3. 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"
    

答案 9 :(得分:0)

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

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

fread = fopen.readlines()

x = input(“输入搜索字符串:”)

对于行中的行:

  if x in line:

      print(line)

答案 10 :(得分:0)

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"

答案 11 :(得分:0)

这是另一个。采取绝对文件路径和给定的字符串,并将其传递给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)