Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在文本文件中搜索字符串?_Python - Fatal编程技术网

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

Python 如何在文本文件中搜索字符串?,python,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:

我想检查文本文件中是否有字符串。如果是,则执行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 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()
的输出:


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"
发现=错误

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(这是falsy)

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


  • 您总是得到
    True
    的原因已经给出,因此我将提供另一个建议:

    如果您的文件不太大,您可以将其读入一个字符串,然后直接使用它(比每行读取和检查更简单,通常更快):

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

    注意:在python 3中,MMAP的行为类似于
    bytearray
    对象而不是字符串,因此使用
    find()
    查找的子序列必须是
    bytes
    对象而不是字符串,例如
    s.find(b'blablabla')


    您还可以在
    mmap
    上使用正则表达式,例如,不区分大小写的搜索:
    如果重新搜索(br'(?i)blablabla',s):

    这里有另一种方法,可以使用find函数回答您的问题,该函数可以为您提供真实位置的文字数字值

    open('file', 'r').read().find('')
    
    在find中写下你想找到的单词
    'file'
    代表您的文件名

    如何搜索文件中的文本并返回找到单词的文件路径 (葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干葡萄干)

    大体上


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

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

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

     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)
    

    还有一个。获取绝对文件路径和给定字符串,并将其传递给word_find(),在enumerate()方法中对给定文件使用readlines()方法,该方法在逐行遍历时给出一个iterable计数,最后给出具有匹配字符串的行以及给定的行号。干杯

      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)
    
    def word_find(文件,word):
    打开(文件“r”)作为目标文件:
    对于num,枚举中的行(target_file.readlines(),1):
    如果str(word)在同一行:
    打印(f'{line}')
    其他:
    打印(f'>{word}未找到。“)
    如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
    文件到进程='/path/to/file'
    字符串到查找=输入()
    word_-find(文件到进程,字符串到查找)
    
    我明白了,现在可以用了。但对我来说似乎有点奇怪,这意味着Python说“模块是真的,除非另有说明”。所以如果我做一个空模块,它总是真的?有趣:)不,一点也不-与模块无关。您只是简单地检查True是否为True,事实就是如此。第二个解决方案与open('example.txt')中的
    'blabla'结果不同。read()
    在我的python 2.7中,奇怪的是,它确实与
    s.find('blablabla')
    一起工作(检查-1)。我敢发誓,它过去也在中使用过。。。但是现在看来,中的
    只适用于单个字符…
    如果打开的'blabla'('example.txt')。read():打印“true”
    ==>在这种情况下,我们如何关闭
    example.txt
    文件?@begueradj:关于mmap解决方案:您应该使用
    find()
    方法(参见前面的注释),我已经相应地更新了答案。
    open
    通常应该封装在
    中,并带有
    语句:
    并带有open(文件名)作为fl:return text in fl.read()
    如果您对此主题有疑问,但本问答没有回答,请在右上角提出一个新问题。除你的答案外,以上所有答案都是非常错误的。我花了半天的时间猜测他们验证的答案到底是怎么回事,而答案完全错了。只有你的为我工作
    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')
    
    #!/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')
    
    open('file', 'r').read().find('')
    
    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
    
    # -*- 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)
    
     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"
    
      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)