Hướng dẫn python replace text in file regex - python thay thế văn bản trong tệp regex

Làm thế nào tôi có thể thay thế các chuỗi trong một tệp bằng cách sử dụng các biểu thức thông thường trong Python?

Tôi muốn mở một tệp trong đó tôi nên thay thế các chuỗi cho các chuỗi khác và chúng tôi cần sử dụng các biểu thức thông thường (tìm kiếm và thay thế). Điều gì sẽ là một số ví dụ về việc mở một tệp và sử dụng nó bằng phương thức tìm kiếm và thay thế?

Hướng dẫn python replace text in file regex - python thay thế văn bản trong tệp regex

hỏi ngày 28 tháng 2 năm 2016 lúc 20:52Feb 28, 2016 at 20:52

Hướng dẫn python replace text in file regex - python thay thế văn bản trong tệp regex

2

# The following code will search 'MM/DD/YYYY' (e.g. 11/30/2016 or NOV/30/2016, etc ),
# and replace with 'MM-DD-YYYY' in multi-line mode.
import re
with open ('input.txt', 'r' ) as f:
    content = f.read()
    content_new = re.sub('(\d{2}|[a-yA-Y]{3})\/(\d{2})\/(\d{4})', r'\1-\2-\3', content, flags = re.M)

Đã trả lời ngày 28 tháng 2 năm 2016 lúc 21:09Feb 28, 2016 at 21:09

QuinnquinnQuinn

4.2542 Huy hiệu vàng20 Huy hiệu bạc18 Huy hiệu đồng2 gold badges20 silver badges18 bronze badges

9

Đây là một định dạng chung. Bạn có thể sử dụng Re.Sub hoặc Re.Match, dựa trên yêu cầu của bạn. Dưới đây là một mẫu chung để mở một tệp và thực hiện nó:

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)

Hướng dẫn python replace text in file regex - python thay thế văn bản trong tệp regex

Đã trả lời ngày 28 tháng 2 năm 2016 lúc 21:01Feb 28, 2016 at 21:01

user2532296user2532296user2532296

7901 Huy hiệu vàng9 Huy hiệu bạc25 Huy hiệu đồng1 gold badge9 silver badges25 bronze badges

3

Trong bài viết này, chúng tôi sẽ học cách tìm kiếm và thay thế một văn bản của một tệp trong Python. Chúng tôi sẽ sử dụng một số chức năng tích hợp và một số mã tùy chỉnh là tốt. Chúng tôi sẽ thay thế văn bản hoặc chuỗi trong một tệp bằng cách sử dụng các cách được đề cập.

Python cung cấp nhiều chức năng tích hợp để thực hiện các hoạt động xử lý tệp. Thay vì tạo một tệp được sửa đổi mới, chúng tôi sẽ tìm kiếm một văn bản từ một tệp và thay thế nó bằng một số văn bản khác trong cùng một tệp. Điều này sửa đổi tệp với dữ liệu mới. Điều này sẽ thay thế tất cả các văn bản phù hợp trong một tệp và giảm chi phí thay đổi từng từ. Hãy để chúng tôi thảo luận về một số cách được đề cập để tìm kiếm và thay thế văn bản trong một tệp trong Python.

Tệp văn bản mẫu

Chúng tôi sẽ sử dụng tệp đánh giá dưới đây.TEXT để sửa đổi nội dung.review.text file to modify the contents.

In the movie Ghost
the joke is built on a rock-solid boundation
the movie would still work played perfectly straight
The notion of a ghost-extermination squad taking on 
the paramal hordes makes a compelling setup for a big-budget adventure of any stripe
Indeed, the film as it stands frequently allows time to pass without a gag
But then comes the punch line: the characters are funny
And because we’ve been hooked by the story, the humor the characters provide is all the richer.

Ví dụ: Sử dụng thay thế () để thay thế một văn bản trong tệp

Ví dụ dưới đây sử dụng hàm replace() để sửa đổi một chuỗi trong một tệp. Chúng tôi sử dụng tệp Review.txt để sửa đổi nội dung. Nó tìm kiếm chuỗi bằng cách sử dụng cho vòng lặp và thay thế chuỗi cũ bằng một chuỗi mới.

open(file,'r') - Nó mở tệp đánh giá.txt để đọc nội dung của tệp.

strip() - Trong khi lặp lại nội dung của tệp, chức năng Dải () dải ngắt dòng cuối.

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
0 - Nó có một chuỗi cũ và một chuỗi mới để thay thế các đối số của nó.

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
1 - Sau khi kết hợp chuỗi mới và thêm ngắt dòng cuối, nó sẽ đóng tệp.

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
2 - Nó mở tệp để viết và ghi đè nội dung tệp cũ với nội dung mới.

reading_file = open("review.txt", "r")

new_file_content = ""
for line in reading_file:
    stripped_line = line.strip()
    new_line = stripped_line.replace("Ghost", "Ghostbusters")
    new_file_content += new_line +"\n"
reading_file.close()

writing_file = open("review.txt", "w")
writing_file.write(new_file_content)
writing_file.close()

Output:

Hướng dẫn python replace text in file regex - python thay thế văn bản trong tệp regex

Ví dụ: Thay thế một văn bản bằng mô -đun regex

Một phương pháp thay thế cho các phương pháp được đề cập ở trên là sử dụng mô-đun Python từ

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
3. Ví dụ dưới đây nhập mô -đun Regex. Nó tạo ra một hàm và truyền một tệp, một chuỗi cũ và một chuỗi mới làm đối số. Bên trong hàm, chúng tôi mở tệp ở cả chế độ đọc và ghi và đọc nội dung của tệp.

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
4 - Nó được sử dụng để biên dịch một mẫu biểu thức thông thường và chuyển đổi nó thành một đối tượng biểu thức chính quy sau đó có thể được sử dụng để khớp.

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
5 - Nó được sử dụng để thoát khỏi các ký tự đặc biệt trong một mẫu. - It is used to escape special characters in a pattern.

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
6 - Nó được sử dụng để thay thế một mẫu bằng một chuỗi. - It is used to replace a pattern with a string.

#importing the regex module
import re

#defining the replace method
def replace(filePath, text, subs, flags=0):
    with open(file_path, "r+") as file:
        #read the file contents
        file_contents = file.read()
        text_pattern = re.compile(re.escape(text), flags)
        file_contents = text_pattern.sub(subs, file_contents)
        file.seek(0)
        file.truncate()
        file.write(file_contents)

    
file_path="review.txt"
text="boundation"
subs="foundation"
#calling the replace method
replace(file_path, text, subs)

Output:

Hướng dẫn python replace text in file regex - python thay thế văn bản trong tệp regex

FileInput trong Python

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
7 là một tính năng hữu ích của Python để thực hiện các hoạt động liên quan đến tệp khác nhau. Để sử dụng FileInput, mô -đun
import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
8 được nhập. Nó là tuyệt vời cho kịch bản vứt bỏ. Nó cũng được sử dụng để thay thế các nội dung trong một tệp. Nó thực hiện tìm kiếm, chỉnh sửa và thay thế trong một tệp văn bản. Nó không tạo ra bất kỳ tệp hoặc chi phí mới nào.

Syntax-

FileInput(filename, inplace=True, backup='.bak')

Parameters-

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
9 - bản sao lưu là một tiện ích mở rộng cho tệp sao lưu được tạo trước khi chỉnh sửa.

Ví dụ: Tìm kiếm và thay thế một văn bản bằng hàm fileInput và thay thế ()

Hàm bên dưới thay thế một văn bản bằng hàm replace().

import fileinput

filename = "review.txt"

with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f:
    for line in f:
        if("paramal" in line):
            print(line.replace("paramal","paranormal"), end ='')
        else:
            print(line, end ='') 

Output:

Hướng dẫn python replace text in file regex - python thay thế văn bản trong tệp regex

Sự kết luận

Trong bài viết này, chúng tôi đã học cách tìm kiếm và thay thế một văn bản hoặc một chuỗi trong một tệp bằng cách sử dụng một số hàm tích hợp trong mô-đun replace(),

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
3 và
import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
7. Chúng tôi đã sử dụng một số mã tùy chỉnh là tốt. Chúng tôi đã thấy đầu ra quá để phân biệt giữa các ví dụ. Do đó, để tìm kiếm và thay thế một chuỗi trong người dùng Python có thể tải toàn bộ tệp và sau đó thay thế nội dung trong cùng một tệp thay vì tạo một tệp mới và sau đó ghi đè lên tệp.

Làm thế nào để bạn thay thế văn bản trong một tệp trong Python?

Để thay thế văn bản trong một tệp, chúng tôi sẽ mở tệp chỉ đọc bằng hàm Open (). Sau đó, chúng tôi sẽ đọc và thay thế nội dung trong tệp văn bản bằng các hàm đọc () và thay thế ().open the file in read-only using the open() function. Then we will t=read and replace the content in the text file using the read() and replace() functions.

Regex có thể được sử dụng với thay thế trong Python không?

Chúng ta có thể sử dụng regex để thay thế nhiều mẫu cùng một lúc bằng regex..

Làm thế nào để bạn thay thế một dòng trong một tệp văn bản trong Python?

Để thay thế một số dòng cụ thể trong một tệp, hãy lặp qua từng dòng trong tệp văn bản và tìm số dòng sẽ được thay thế và sau đó thay thế nó bằng chuỗi mới bằng phương thức thay thế ().loop through each line in the text file and find the line number to be replaced and then replace it with the new string using the replace() method.

Làm thế nào bạn sẽ cập nhật nội dung của một tệp sang một tệp khác trong Python?

Thuật toán:..
Nhập tên của các tệp ..
Mở cả hai tệp trong chế độ chỉ đọc bằng hàm Open () ..
In nội dung của các tệp trước khi nối thêm hàm Read () ..
Đóng cả hai tệp bằng hàm đóng () ..
Mở tệp đầu tiên ở chế độ phụ lục và tệp thứ hai ở chế độ đọc ..