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ế?
Đâ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ó:
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:
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:
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.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:
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.Để 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.
Để 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.