Hướng dẫn find index of string in text file python - tìm chỉ mục của chuỗi trong tệp văn bản python

Ví dụ, tôi có tệp và từ "kiểm tra". Tệp là một phần nhị phân nhưng có chuỗi "kiểm tra". Làm thế nào để tìm vị trí của từ (chỉ mục) trong tệp không tải vào bộ nhớ tệp này?

Show

Hướng dẫn find index of string in text file python - tìm chỉ mục của chuỗi trong tệp văn bản python

DOT NET

4.86312 Huy hiệu vàng52 Huy hiệu bạc97 Huy hiệu Đồng12 gold badges52 silver badges97 bronze badges

Hỏi ngày 8 tháng 8 năm 2011 lúc 10:43Aug 8, 2011 at 10:43

3

Bạn không thể tìm thấy vị trí của một văn bản trong một tệp trừ khi bạn mở tệp. Nó giống như yêu cầu ai đó đọc một tờ báo mà không mở mắt.

Để trả lời phần đầu tiên của câu hỏi của bạn, nó tương đối đơn giản.

with open('Path/to/file', 'r') as f:
    content = f.read()
    print content.index('test')

Đã trả lời ngày 28 tháng 9 năm 2013 lúc 7:44Sep 28, 2013 at 7:44

Pankaj Parasharpankaj ParasharPankaj Parashar

9.3245 huy hiệu vàng34 Huy hiệu bạc47 Huy hiệu đồng5 gold badges34 silver badges47 bronze badges

Bạn có thể sử dụng các tệp ánh xạ bộ nhớ và biểu thức thông thường.

Các đối tượng tệp được ánh xạ bộ nhớ hoạt động giống như cả hai chuỗi và thích các đối tượng tệp. Tuy nhiên, không giống như các đối tượng chuỗi bình thường, chúng là có thể thay đổi. Bạn có thể sử dụng các đối tượng MMAP ở hầu hết các nơi mà chuỗi được mong đợi; Ví dụ: bạn có thể sử dụng mô-đun RE để tìm kiếm thông qua tệp ánh xạ bộ nhớ. Vì chúng có thể thay đổi, bạn có thể thay đổi một ký tự duy nhất bằng cách thực hiện obj [index] = 'a' hoặc thay đổi một chuỗi con bằng cách gán cho một lát: obj [i1: i2] = '...'. Bạn cũng có thể đọc và ghi dữ liệu bắt đầu ở vị trí tệp hiện tại và tìm kiếm () thông qua tệp đến các vị trí khác nhau.for example, you can use the re module to search through a memory-mapped file. Since they’re mutable, you can change a single character by doing obj[index] = 'a', or change a substring by assigning to a slice: obj[i1:i2] = '...'. You can also read and write data starting at the current file position, and seek() through the file to different positions.

Thí dụ

import re
import mmap

f = open('path/filename', 'r+b')
mf = mmap.mmap(f.fileno(), 0)
mf.seek(0) # reset file cursor
m = re.search('pattern', mf)
print m.start(), m.end()
mf.close()
f.close()

Đã trả lời ngày 8 tháng 8 năm 2011 lúc 11:10Aug 8, 2011 at 11:10

Nick Dandoulakisnick DandoulakisNick Dandoulakis

41.9K15 Huy hiệu vàng102 Huy hiệu bạc136 Huy hiệu đồng15 gold badges102 silver badges136 bronze badges

0

Thử cái này:

with open(file_dmp_path, 'rb') as file:
fsize = bsize = os.path.getsize(file_dmp_path)
word_len = len(SEARCH_WORD)
while True:
    p = file.read(bsize).find(SEARCH_WORD)
    if p > -1:
        pos_dec = file.tell() - (bsize - p)
        file.seek(pos_dec + word_len)
        bsize = fsize - file.tell()
    if file.tell() < fsize:
        seek = file.tell() - word_len + 1
        file.seek(seek)
    else:
        break

Đã trả lời ngày 28 tháng 9 năm 2013 lúc 6:06Sep 28, 2013 at 6:06

Bài tập và câu đố Python

Các bài tập mã hóa miễn phí và các câu đố bao gồm các vấn đề cơ bản của Python, cấu trúc dữ liệu, phân tích dữ liệu, v.v.

  • Hơn 15 bài tập và câu đố dành riêng cho chủ đề
  • Mỗi bài tập chứa 10 câu hỏi
  • Mỗi bài kiểm tra chứa 12-15 mcq
  • Tìm kiếm chuỗi trong nhiều tệp

Đôi khi bạn muốn tìm kiếm một chuỗi trong nhiều tệp có trong một thư mục. Sử dụng các bước dưới đây để tìm kiếm một văn bản trong tất cả các tệp của một thư mục.

Liệt kê tất cả các tệp của một thư mục

Đọc từng tệp một

  1. Tiếp theo, tìm kiếm một từ trong tệp đã cho. Nếu tìm thấy, hãy ngừng đọc các tập tin.

    Tìm kiếm tệp cho một danh sách các chuỗi

  2. Đôi khi bạn muốn tìm kiếm một tệp cho nhiều chuỗi. Ví dụ dưới đây cho thấy cách tìm kiếm tệp văn bản cho bất kỳ từ nào trong danh sách.

    Bài tập và câu đố Python

  3. Các bài tập mã hóa miễn phí và các câu đố bao gồm các vấn đề cơ bản của Python, cấu trúc dữ liệu, phân tích dữ liệu, v.v.

    Hơn 15 bài tập và câu đố dành riêng cho chủ đề

  4. Mỗi bài tập chứa 10 câu hỏi

    Mỗi bài kiểm tra chứa 12-15 mcq

Trong hướng dẫn Python này, bạn sẽ học cách tìm kiếm một chuỗi trong một tệp văn bản. Ngoài ra, chúng tôi sẽ thấy cách tìm kiếm một chuỗi trong một tệp và in số dòng và dòng của nó.

Sau khi đọc bài viết này, bạn sẽ học các trường hợp sau.

Hướng dẫn find index of string in text file python - tìm chỉ mục của chuỗi trong tệp văn bản python

def search_str(file_path, word):
    with open(file_path, 'r') as file:
        # read all content of a file
        content = file.read()
        # check if string present in a file
        if word in content:
            print('string exist in a file')
        else:
            print('string does not exist in a file')

search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')

Output::

string exists in a file

Nếu một tệp nhỏ, hãy đọc nó vào một chuỗi và sử dụng phương thức import re import mmap f = open('path/filename', 'r+b') mf = mmap.mmap(f.fileno(), 0) mf.seek(0) # reset file cursor m = re.search('pattern', mf) print m.start(), m.end() mf.close() f.close() 5 để kiểm tra xem một chuỗi hoặc từ có có trong một tệp không. (dễ dàng và nhanh hơn so với đọc và kiểm tra dòng trên mỗi dòng)

Nếu một tệp lớn, hãy sử dụng MMAP để tìm kiếm một chuỗi trong một tệp. Chúng tôi không cần phải đọc toàn bộ tệp trong bộ nhớ, điều này sẽ làm cho bộ nhớ giải pháp của chúng tôi hiệu quả.

  • Tìm kiếm một chuỗi trong nhiều tệp
  • Chúng tôi sẽ thấy từng giải pháp từng cái một.
  • Tiếp theo, sử dụng một vòng lặp để lặp từng dòng từ một tệp.
  • Tiếp theo, trong mỗi lần lặp của một vòng lặp, sử dụng điều kiện IF để kiểm tra xem một chuỗi có mặt trong một dòng hiện tại và in số dòng và dòng dòng hiện tại.

Ví dụ: Trong ví dụ này, chúng tôi sẽ tìm kiếm chuỗi ‘máy tính xách tay trong một tệp, in dòng của nó cùng với số dòng.: In this example, we’ll search the string ‘laptop’ in a file, print its line along with the line number.

# string to search in file
word = 'laptop'
with open(r'E:\demos\files_demos\account\sales.txt', 'r') as fp:
    # read all lines in a list
    lines = fp.readlines()
    for line in lines:
        # check if string present on a current line
        if line.find(word) != -1:
            print(word, 'string exists in file')
            print('Line Number:', lines.index(line))
            print('Line:', line)

Output::

laptop string exists in a file
line: laptop 10 15000
line number: 1

Lưu ý: Bạn cũng có thể sử dụng phương thức

with open(file_dmp_path, 'rb') as file:
fsize = bsize = os.path.getsize(file_dmp_path)
word_len = len(SEARCH_WORD)
while True:
    p = file.read(bsize).find(SEARCH_WORD)
    if p > -1:
        pos_dec = file.tell() - (bsize - p)
        file.seek(pos_dec + word_len)
        bsize = fsize - file.tell()
    if file.tell() < fsize:
        seek = file.tell() - word_len + 1
        file.seek(seek)
    else:
        break
9 thay vì
def search_str(file_path, word):
    with open(file_path, 'r') as file:
        # read all content of a file
        content = file.read()
        # check if string present in a file
        if word in content:
            print('string exist in a file')
        else:
            print('string does not exist in a file')

search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')
0 để đọc từng dòng tệp, hãy dừng lại khi bạn đã đến các dòng bạn muốn. Sử dụng kỹ thuật này, chúng tôi không cần phải đọc toàn bộ tập tin.
: You can also use the
with open(file_dmp_path, 'rb') as file:
fsize = bsize = os.path.getsize(file_dmp_path)
word_len = len(SEARCH_WORD)
while True:
    p = file.read(bsize).find(SEARCH_WORD)
    if p > -1:
        pos_dec = file.tell() - (bsize - p)
        file.seek(pos_dec + word_len)
        bsize = fsize - file.tell()
    if file.tell() < fsize:
        seek = file.tell() - word_len + 1
        file.seek(seek)
    else:
        break
9 method instead of
def search_str(file_path, word):
    with open(file_path, 'r') as file:
        # read all content of a file
        content = file.read()
        # check if string present in a file
        if word in content:
            print('string exist in a file')
        else:
            print('string does not exist in a file')

search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')
0 to read a file line by line, stop when you’ve gotten to the lines you want. Using this technique, we don’t need to read the entire file.

Cách hiệu quả để tìm kiếm chuỗi trong một tệp văn bản lớn

Tất cả các cách trên đọc toàn bộ tệp trong bộ nhớ. Nếu tệp lớn, đọc toàn bộ tệp trong bộ nhớ là không lý tưởng.

Trong phần này, chúng tôi sẽ thấy cách nhanh nhất và tiết kiệm bộ nhớ nhất để tìm kiếm một chuỗi trong một tệp văn bản lớn.

  • Mở tệp ở chế độ đọc
  • Sử dụng cho vòng lặp với hàm
    def search_str(file_path, word):
        with open(file_path, 'r') as file:
            # read all content of a file
            content = file.read()
            # check if string present in a file
            if word in content:
                print('string exist in a file')
            else:
                print('string does not exist in a file')
    
    search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')
    1 để có được một dòng và số của nó. Hàm
    def search_str(file_path, word):
        with open(file_path, 'r') as file:
            # read all content of a file
            content = file.read()
            # check if string present in a file
            if word in content:
                print('string exist in a file')
            else:
                print('string does not exist in a file')
    
    search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')
    1 thêm một bộ đếm cho một điều khác nhau và trả về nó trong việc liệt kê đối tượng. Chuyển thanh trỏ tệp được trả về bởi hàm
    import re
    import mmap
    
    f = open('path/filename', 'r+b')
    mf = mmap.mmap(f.fileno(), 0)
    mf.seek(0) # reset file cursor
    m = re.search('pattern', mf)
    print m.start(), m.end()
    mf.close()
    f.close()
    
    8 cho
    def search_str(file_path, word):
        with open(file_path, 'r') as file:
            # read all content of a file
            content = file.read()
            # check if string present in a file
            if word in content:
                print('string exist in a file')
            else:
                print('string does not exist in a file')
    
    search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')
    1.
  • Chúng ta có thể sử dụng đối tượng liệt kê này với một vòng lặp để truy cập vào từng dòng và số dòng.

Lưu ý:

def search_str(file_path, word):
    with open(file_path, 'r') as file:
        # read all content of a file
        content = file.read()
        # check if string present in a file
        if word in content:
            print('string exist in a file')
        else:
            print('string does not exist in a file')

search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')
5 không tải toàn bộ tệp trong bộ nhớ, vì vậy đây là một giải pháp hiệu quả.: The
def search_str(file_path, word):
    with open(file_path, 'r') as file:
        # read all content of a file
        content = file.read()
        # check if string present in a file
        if word in content:
            print('string exist in a file')
        else:
            print('string does not exist in a file')

search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')
5 doesn’t load the entire file in memory, so this is an efficient solution.

Example::

with open(r"E:\demos\files_demos\account\sales.txt", 'r') as fp:
    for l_no, line in enumerate(fp):
        # search string
        if 'laptop' in line:
            print('string found in a file')
            print('Line Number:', l_no)
            print('Line:', line)
            # don't look for next lines
            break

Example::

string found in a file
Line Number: 1
Line: laptop 10 15000

mmap để tìm kiếm một chuỗi trong tệp văn bản

Trong phần này, chúng tôi sẽ thấy cách nhanh nhất và tiết kiệm bộ nhớ nhất để tìm kiếm một chuỗi trong một tệp văn bản lớn.

Mở tệp ở chế độ đọc

Example::

import mmap

with open(r'E:\demos\files_demos\account\sales.txt', 'rb', 0) as file:
    s = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
    if s.find(b'laptop') != -1:
        print('string exist in a file')

Output::

import re
import mmap

f = open('path/filename', 'r+b')
mf = mmap.mmap(f.fileno(), 0)
mf.seek(0) # reset file cursor
m = re.search('pattern', mf)
print m.start(), m.end()
mf.close()
f.close()
0

Sử dụng cho vòng lặp với hàm def search_str(file_path, word): with open(file_path, 'r') as file: # read all content of a file content = file.read() # check if string present in a file if word in content: print('string exist in a file') else: print('string does not exist in a file') search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')1 để có được một dòng và số của nó. Hàm def search_str(file_path, word): with open(file_path, 'r') as file: # read all content of a file content = file.read() # check if string present in a file if word in content: print('string exist in a file') else: print('string does not exist in a file') search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')1 thêm một bộ đếm cho một điều khác nhau và trả về nó trong việc liệt kê đối tượng. Chuyển thanh trỏ tệp được trả về bởi hàm import re import mmap f = open('path/filename', 'r+b') mf = mmap.mmap(f.fileno(), 0) mf.seek(0) # reset file cursor m = re.search('pattern', mf) print m.start(), m.end() mf.close() f.close() 8 cho def search_str(file_path, word): with open(file_path, 'r') as file: # read all content of a file content = file.read() # check if string present in a file if word in content: print('string exist in a file') else: print('string does not exist in a file') search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')1.

Chúng ta có thể sử dụng đối tượng liệt kê này với một vòng lặp để truy cập vào từng dòng và số dòng.

  • Lưu ý:
    def search_str(file_path, word):
        with open(file_path, 'r') as file:
            # read all content of a file
            content = file.read()
            # check if string present in a file
            if word in content:
                print('string exist in a file')
            else:
                print('string does not exist in a file')
    
    search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')
    5 không tải toàn bộ tệp trong bộ nhớ, vì vậy đây là một giải pháp hiệu quả.
  • mmap để tìm kiếm một chuỗi trong tệp văn bản
  • Ngoài ra, bạn có thể sử dụng mô -đun MMAP để tìm một chuỗi trong một tệp lớn. Phương thức
    def search_str(file_path, word):
        with open(file_path, 'r') as file:
            # read all content of a file
            content = file.read()
            # check if string present in a file
            if word in content:
                print('string exist in a file')
            else:
                print('string does not exist in a file')
    
    search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')
    6 tạo đối tượng
    def search_str(file_path, word):
        with open(file_path, 'r') as file:
            # read all content of a file
            content = file.read()
            # check if string present in a file
            if word in content:
                print('string exist in a file')
            else:
                print('string does not exist in a file')
    
    search_str(r'E:\demos\files_demos\account\sales.txt', 'laptop')
    7 kiểm tra tệp bên dưới thay vì đọc toàn bộ tệp trong bộ nhớ.

Example::

import re
import mmap

f = open('path/filename', 'r+b')
mf = mmap.mmap(f.fileno(), 0)
mf.seek(0) # reset file cursor
m = re.search('pattern', mf)
print m.start(), m.end()
mf.close()
f.close()
1

Output::

import re
import mmap

f = open('path/filename', 'r+b')
mf = mmap.mmap(f.fileno(), 0)
mf.seek(0) # reset file cursor
m = re.search('pattern', mf)
print m.start(), m.end()
mf.close()
f.close()
2

Tìm kiếm chuỗi trong nhiều tệp

Đôi khi bạn muốn tìm kiếm một chuỗi trong nhiều tệp có trong một thư mục. Sử dụng các bước dưới đây để tìm kiếm một văn bản trong tất cả các tệp của một thư mục.

Example::

import re
import mmap

f = open('path/filename', 'r+b')
mf = mmap.mmap(f.fileno(), 0)
mf.seek(0) # reset file cursor
m = re.search('pattern', mf)
print m.start(), m.end()
mf.close()
f.close()
3

Output::

import re
import mmap

f = open('path/filename', 'r+b')
mf = mmap.mmap(f.fileno(), 0)
mf.seek(0) # reset file cursor
m = re.search('pattern', mf)
print m.start(), m.end()
mf.close()
f.close()
0

Liệt kê tất cả các tệp của một thư mục

Đọc từng tệp một

  • Tiếp theo, tìm kiếm một từ trong tệp đã cho. Nếu tìm thấy, hãy ngừng đọc các tập tin.Topic-specific Exercises and Quizzes
  • Tìm kiếm tệp cho một danh sách các chuỗi
  • Đôi khi bạn muốn tìm kiếm một tệp cho nhiều chuỗi. Ví dụ dưới đây cho thấy cách tìm kiếm tệp văn bản cho bất kỳ từ nào trong danh sách.