텍스트 파일에서 문자열을 검색하려면 어떻게 해야 합니까?
텍스트 파일에 문자열이 있는지 확인하고 싶습니다.그렇다면 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"
당신이 항상 얻은 이유는True
이미 제공되었으므로 다른 제안을 드리겠습니다.
파일이 너무 크지 않으면 문자열로 읽고 사용할 수 있습니다(한 줄당 읽고 확인하는 것보다 쉽고 종종 빠릅니다).
with open('example.txt') as f:
if 'blabla' in f.read():
print("true")
또 다른 방법: 를 사용하여 (메모리 내의 파일 전체를 읽는 대신) 기본 파일을 사용하는 "string-like" 개체를 생성함으로써 발생할 수 있는 메모리 문제를 완화할 수 있습니다.
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):
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')
여기 무엇이 실제로 어디에 있는지 문자 그대로 수치로 알려주는 찾기 기능을 사용하여 질문에 대답할 수 있는 또 다른 방법이 있습니다.
open('file', 'r').read().find('')
찾고 싶은 단어를 쓰고'file'
파일명을 나타냅니다.
if True:
print "true"
True는 항상 True이기 때문에 항상 발생합니다.
이런 걸 원하십니까?
if check():
print "true"
else:
print "false"
행운을 빕니다.
저는 이 목적을 위해 작은 기능을 만들었습니다.입력 파일에서 단어를 검색한 다음 출력 파일에 추가합니다.
def searcher(outf, inf, string):
with open(outf, 'a') as f1:
if string in open(inf).read():
f1.write(string)
- outf는 출력 파일입니다.
- inf는 입력 파일입니다.
- string은 물론 검색하여 outf에 추가하는 원하는 문자열입니다.
당신의.check
함수가 반환해야 합니다.found
boolean을 사용하여 인쇄할 항목을 결정합니다.
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"
두 가지 문제:
함수는 아무것도 반환하지 않습니다.명시적으로 아무것도 반환하지 않는 함수는 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"
파일 내의 텍스트를 검색하여 단어를 찾을 수 있는 파일 경로를 반환하는 방법(파일 경로 반환하는 방법)
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
사용자가 지정된 텍스트 파일에서 단어를 검색하려는 경우.
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 "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 "found"
else:
print "not found"
여기 또 있어요.절대 파일 경로와 지정된 문자열을 사용하여 word_find()에 전달합니다.이 메서드는 1줄씩 이동할 때 반복 가능한 카운트를 제공하는 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 other" 문이 함수를 벗어나기 때문에 함수에 전역 변수로 생성되어야 합니다.루프 코드를 끊기 위해 "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")
언급URL : https://stackoverflow.com/questions/4940032/how-to-search-for-a-string-in-text-files
'source' 카테고리의 다른 글
Python에서 텍스트 파일을 연결하려면 어떻게 해야 하나요? (0) | 2022.10.06 |
---|---|
Symfony 2 Entity Manager 주입 인 서비스 (0) | 2022.10.06 |
불변형 및 가변형 (0) | 2022.10.06 |
mysql.sock을 통한 고부하 시 PHP/MYSQL 연결 실패 (0) | 2022.10.06 |
MySQL의 ORDER BY RAND() 함수를 최적화하려면 어떻게 해야 합니까? (0) | 2022.09.23 |