Hướng dẫn python replace multiple strings in file - python thay thế nhiều chuỗi trong tệp

Bạn có thể thay thế nội dung của văn bản hoặc tệp bằng Sub từ mô -đun Regex (Re):sub from the regex module (re):

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)

    return target

Hoặc chỉ với str.replace không cần từ nhập lại phụ:str.replace which does not need from re import sub:

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target

Đây là triển khai đầy đủ:

from re import sub
from os.path import abspath, realpath, join, dirname

file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()

new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')


def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
        # target = target.replace(check, replacer)

    return target


# check : replacer
dict_replace = {
    'ipsum': 'XXXXXXX',
    'amet,': '***********',
    'dolor': '$$$$$'
}

new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet

print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet

Bài viết này mô tả cách thay thế các chuỗi trong Python.

  • Thay thế chất nền:
    s = 'one two one two one'
    
    print(s.replace(' ', '-'))
    # one-two-one-two-one
    
    1
    • Cách sử dụng cơ bản
    • Chỉ định số lượng thay thế tối đa:
      s = 'one two one two one'
      
      print(s.replace(' ', '-'))
      # one-two-one-two-one
      
      2
    • Thay thế nhiều chuỗi con khác nhau
    • Chuỗi hoán đổi
    • Thay thế ký tự mới
  • Thay thế nhiều ký tự khác nhau:
    s = 'one two one two one'
    
    print(s.replace(' ', '-'))
    # one-two-one-two-one
    
    3
    • Cách sử dụng cơ bản
    • Chỉ định số lượng thay thế tối đa:
      s = 'one two one two one'
      
      print(s.replace(' ', '-'))
      # one-two-one-two-one
      
      2
  • Thay thế nhiều chuỗi con khác nhau
    • Cách sử dụng cơ bản
    • Chỉ định số lượng thay thế tối đa:
      s = 'one two one two one'
      
      print(s.replace(' ', '-'))
      # one-two-one-two-one
      
      2
    • Thay thế bằng cách sử dụng phần phù hợp
    • Nhận số lượng các bộ phận thay thế
  • Thay thế theo vị trí: Cắt lát

Không có phương pháp để thay thế chuỗi ở vị trí được chỉ định.

  • Bằng cách chia chuỗi bằng một lát và nối chúng với một chuỗi khác, bạn có thể tạo một chuỗi mới với vị trí được chỉ định được thay thế.

Độ dài của chuỗi (số lượng ký tự) có thể được lấy bằng

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
01, do đó nó có thể được viết như sau:

  • Nhận độ dài của một chuỗi (số lượng ký tự) trong Python

Thay thế chất nền: s = 'one two one two one' print(s.replace(' ', '-')) # one-two-one-two-one 1

Cách sử dụng cơ bản

Chỉ định số lượng thay thế tối đa:

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
2

  • Thay thế nhiều chuỗi con khác nhau

Chuỗi hoán đổi

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one

Thay thế ký tự mới

print(s.replace(' ', ''))
# onetwoonetwoone

Chỉ định số lượng thay thế tối đa: s = 'one two one two one' print(s.replace(' ', '-')) # one-two-one-two-one 2

Thay thế nhiều chuỗi con khác nhau

print(s.replace('one', 'XXX'))
# XXX two XXX two XXX

print(s.replace('one', 'XXX', 2))
# XXX two XXX two one

Thay thế nhiều chuỗi con khác nhau

Chuỗi hoán đổi

Thay thế ký tự mới

print(s.replace('one', 'XXX').replace('two', 'YYY'))
# XXX YYY XXX YYY XXX

Nó chỉ gọi

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
1 theo thứ tự, vì vậy nếu
print(s.replace(' ', ''))
# onetwoonetwoone
0 đầu tiên chứa
s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
9 sau đây, thì
print(s.replace(' ', ''))
# onetwoonetwoone
0 đầu tiên cũng được thay thế.

print(s.replace('one', 'XtwoX').replace('two', 'YYY'))
# XYYYX YYY XYYYX YYY XYYYX

print(s.replace('two', 'YYY').replace('one', 'XtwoX'))
# XtwoX YYY XtwoX YYY XtwoX

Để thay thế nhiều ký tự (chuỗi có độ dài

print(s.replace('one', 'XXX'))
# XXX two XXX two XXX

print(s.replace('one', 'XXX', 2))
# XXX two XXX two one
3), bạn có thể sử dụng phương thức
s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
3 được mô tả dưới đây.

Chuỗi hoán đổi

Nếu bạn muốn trao đổi hai chuỗi, việc thay thế chúng theo thứ tự như mô tả ở trên có thể không hoạt động.

print(s.replace('one', 'two').replace('two', 'one'))
# one one one one one

Đầu tiên, bạn nên thay thế nó bằng một chuỗi khác.

print(s.replace('one', 'X').replace('two', 'one').replace('X', 'two'))
# two one two one two

Hoạt động này có thể được biến thành một chức năng như sau:

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
0

Lưu ý rằng chức năng này không hoạt động nếu chuỗi tạm thời

print(s.replace('one', 'XXX'))
# XXX two XXX two XXX

print(s.replace('one', 'XXX', 2))
# XXX two XXX two one
5 được bao gồm trong chuỗi gốc. Nếu bạn muốn làm cho nó nghiêm ngặt, bạn cần kiểm tra xem chuỗi tạm thời
print(s.replace('one', 'XXX'))
# XXX two XXX two XXX

print(s.replace('one', 'XXX', 2))
# XXX two XXX two one
5 có được bao gồm trong chuỗi gốc không và nếu vậy, hãy sử dụng một chuỗi khác cho
print(s.replace('one', 'XXX'))
# XXX two XXX two XXX

print(s.replace('one', 'XXX', 2))
# XXX two XXX two one
5. Trong ví dụ trên,
print(s.replace('one', 'XXX'))
# XXX two XXX two XXX

print(s.replace('one', 'XXX', 2))
# XXX two XXX two one
5 được đặt thành một chuỗi không có ý nghĩa cụ thể.

Để trao đổi nhiều ký tự (chuỗi có độ dài

print(s.replace('one', 'XXX'))
# XXX two XXX two XXX

print(s.replace('one', 'XXX', 2))
# XXX two XXX two one
3), bạn có thể sử dụng phương thức
s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
3 được mô tả dưới đây.

Thay thế ký tự mới

Nếu chuỗi chỉ chứa một loại ký tự dòng mới, bạn có thể chỉ định nó là đối số đầu tiên của

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
1.

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
1

Hãy cẩn thận nếu

print(s.replace('one', 'XXX').replace('two', 'YYY'))
# XXX YYY XXX YYY XXX
2 (LF, được sử dụng trong HĐH UNIX bao gồm Mac) và
print(s.replace('one', 'XXX').replace('two', 'YYY'))
# XXX YYY XXX YYY XXX
3 (Cr + LF, được sử dụng trong OS Windows) được trộn lẫn. Vì
print(s.replace('one', 'XXX').replace('two', 'YYY'))
# XXX YYY XXX YYY XXX
2 được bao gồm trong
print(s.replace('one', 'XXX').replace('two', 'YYY'))
# XXX YYY XXX YYY XXX
3, bạn không thể nhận được kết quả mong muốn tùy theo thứ tự.

Bạn có thể sử dụng

print(s.replace('one', 'XXX').replace('two', 'YYY'))
# XXX YYY XXX YYY XXX
6, trả về danh sách phân chia với các ký tự mới khác nhau và
print(s.replace('one', 'XXX').replace('two', 'YYY'))
# XXX YYY XXX YYY XXX
7, kết hợp danh sách với các chuỗi. Bằng cách này là an toàn và được khuyến nghị, đặc biệt nếu bạn không biết những nhân vật mới được bao gồm những gì.

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
2

Xem bài viết sau đây cho các hoạt động khác liên quan đến việc phá vỡ dòng trong chuỗi.

  • Xử lý các lần phá vỡ dòng (Newlines) trong Python

Thay thế nhiều ký tự khác nhau: s = 'one two one two one' print(s.replace(' ', '-')) # one-two-one-two-one 3

Cách sử dụng cơ bản

Sử dụng phương thức

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
3 để thay thế nhiều ký tự khác nhau. Bạn có thể tạo bảng dịch được chỉ định trong
s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
3 bởi
print(s.replace('one', 'XtwoX').replace('two', 'YYY'))
# XYYYX YYY XYYYX YYY XYYYX

print(s.replace('two', 'YYY').replace('one', 'XtwoX'))
# XtwoX YYY XtwoX YYY XtwoX
1.

  • str.translate () - Python 3.10.8 Tài liệu
  • str.maketrans () - Python 3.10.8 Tài liệu

Chỉ định một từ điển có khóa là ký tự cũ và có giá trị là chuỗi mới trong

print(s.replace('one', 'XtwoX').replace('two', 'YYY'))
# XYYYX YYY XYYYX YYY XYYYX

print(s.replace('two', 'YYY').replace('one', 'XtwoX'))
# XtwoX YYY XtwoX YYY XtwoX
1.

Nhân vật cũ phải là một ký tự (một chuỗi có độ dài

print(s.replace('one', 'XXX'))
# XXX two XXX two XXX

print(s.replace('one', 'XXX', 2))
# XXX two XXX two one
3). Chuỗi mới là một chuỗi hoặc
print(s.replace('one', 'XtwoX').replace('two', 'YYY'))
# XYYYX YYY XYYYX YYY XYYYX

print(s.replace('two', 'YYY').replace('one', 'XtwoX'))
# XtwoX YYY XtwoX YYY XtwoX
4, trong đó
print(s.replace('one', 'XtwoX').replace('two', 'YYY'))
# XYYYX YYY XYYYX YYY XYYYX

print(s.replace('two', 'YYY').replace('one', 'XtwoX'))
# XtwoX YYY XtwoX YYY XtwoX
4 loại bỏ các ký tự cũ.

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
3

Đối số đầu tiên là một chuỗi trong đó các ký tự cũ được nối, thứ hai là một chuỗi trong đó các ký tự mới được nối và thứ ba là một chuỗi trong đó các ký tự bị xóa được nối. Đối số thứ ba là tùy chọn.

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
4

Trong trường hợp này, độ dài của các đối số thứ nhất và thứ hai phải khớp.

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
5

Trao đổi ký tự

Bạn có thể trao đổi các ký tự với

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
3.

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
6

Thay thế bằng regex: s = 'one two one two one' print(s.replace(' ', '-')) # one-two-one-two-one 4, s = 'one two one two one' print(s.replace(' ', '-')) # one-two-one-two-one 5

Nếu bạn muốn thay thế một chuỗi phù hợp với biểu thức thông thường (regex) thay vì kết hợp hoàn hảo, hãy sử dụng

print(s.replace('one', 'XtwoX').replace('two', 'YYY'))
# XYYYX YYY XYYYX YYY XYYYX

print(s.replace('two', 'YYY').replace('one', 'XtwoX'))
# XtwoX YYY XtwoX YYY XtwoX
9 của mô -đun RE.

  • Re.sub () - Hoạt động biểu thức thường xuyên - Python 3.10.8 Tài liệu

Cách sử dụng cơ bản

Sử dụng phương thức

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
3 để thay thế nhiều ký tự khác nhau. Bạn có thể tạo bảng dịch được chỉ định trong
s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
3 bởi
print(s.replace('one', 'XtwoX').replace('two', 'YYY'))
# XYYYX YYY XYYYX YYY XYYYX

print(s.replace('two', 'YYY').replace('one', 'XtwoX'))
# XtwoX YYY XtwoX YYY XtwoX
1.

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
7

str.translate () - Python 3.10.8 Tài liệu

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
8

str.maketrans () - Python 3.10.8 Tài liệu

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
9

Chỉ định một từ điển có khóa là ký tự cũ và có giá trị là chuỗi mới trong print(s.replace('one', 'XtwoX').replace('two', 'YYY')) # XYYYX YYY XYYYX YYY XYYYX print(s.replace('two', 'YYY').replace('one', 'XtwoX')) # XtwoX YYY XtwoX YYY XtwoX 1.

Nhân vật cũ phải là một ký tự (một chuỗi có độ dài

print(s.replace('one', 'XXX'))
# XXX two XXX two XXX

print(s.replace('one', 'XXX', 2))
# XXX two XXX two one
3). Chuỗi mới là một chuỗi hoặc
print(s.replace('one', 'XtwoX').replace('two', 'YYY'))
# XYYYX YYY XYYYX YYY XYYYX

print(s.replace('two', 'YYY').replace('one', 'XtwoX'))
# XtwoX YYY XtwoX YYY XtwoX
4, trong đó
print(s.replace('one', 'XtwoX').replace('two', 'YYY'))
# XYYYX YYY XYYYX YYY XYYYX

print(s.replace('two', 'YYY').replace('one', 'XtwoX'))
# XtwoX YYY XtwoX YYY XtwoX
4 loại bỏ các ký tự cũ.

Đối số đầu tiên là một chuỗi trong đó các ký tự cũ được nối, thứ hai là một chuỗi trong đó các ký tự mới được nối và thứ ba là một chuỗi trong đó các ký tự bị xóa được nối. Đối số thứ ba là tùy chọn.

from re import sub
from os.path import abspath, realpath, join, dirname

file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()

new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')


def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
        # target = target.replace(check, replacer)

    return target


# check : replacer
dict_replace = {
    'ipsum': 'XXXXXXX',
    'amet,': '***********',
    'dolor': '$$$$$'
}

new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet

print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
0

Trong trường hợp này, độ dài của các đối số thứ nhất và thứ hai phải khớp.

from re import sub
from os.path import abspath, realpath, join, dirname

file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()

new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')


def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
        # target = target.replace(check, replacer)

    return target


# check : replacer
dict_replace = {
    'ipsum': 'XXXXXXX',
    'amet,': '***********',
    'dolor': '$$$$$'
}

new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet

print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
1

Trao đổi ký tự

Bạn có thể trao đổi các ký tự với

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
3.

from re import sub
from os.path import abspath, realpath, join, dirname

file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()

new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')


def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
        # target = target.replace(check, replacer)

    return target


# check : replacer
dict_replace = {
    'ipsum': 'XXXXXXX',
    'amet,': '***********',
    'dolor': '$$$$$'
}

new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet

print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
2

Thay thế bằng regex:

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
4,
s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
5

  • Nếu bạn muốn thay thế một chuỗi phù hợp với biểu thức thông thường (regex) thay vì kết hợp hoàn hảo, hãy sử dụng
    print(s.replace('one', 'XtwoX').replace('two', 'YYY'))
    # XYYYX YYY XYYYX YYY XYYYX
    
    print(s.replace('two', 'YYY').replace('one', 'XtwoX'))
    # XtwoX YYY XtwoX YYY XtwoX
    
    9 của mô -đun RE.

Re.sub () - Hoạt động biểu thức thường xuyên - Python 3.10.8 Tài liệu

from re import sub
from os.path import abspath, realpath, join, dirname

file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()

new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')


def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
        # target = target.replace(check, replacer)

    return target


# check : replacer
dict_replace = {
    'ipsum': 'XXXXXXX',
    'amet,': '***********',
    'dolor': '$$$$$'
}

new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet

print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
3

Trong

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
4, chỉ định mẫu regex trong đối số đầu tiên, một chuỗi mới trong chuỗi thứ hai và một chuỗi được xử lý trong chuỗi thứ ba.

  • Biểu cảm lambda trong python

from re import sub
from os.path import abspath, realpath, join, dirname

file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()

new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')


def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
        # target = target.replace(check, replacer)

    return target


# check : replacer
dict_replace = {
    'ipsum': 'XXXXXXX',
    'amet,': '***********',
    'dolor': '$$$$$'
}

new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet

print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
4

Nhận số lượng các bộ phận thay thế

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
5 Trả về một bộ của chuỗi thay thế và số lượng các bộ phận được thay thế.

  • Re.subn () - Hoạt động biểu thức thường xuyên - Python 3.10.8 Tài liệu

from re import sub
from os.path import abspath, realpath, join, dirname

file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()

new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')


def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
        # target = target.replace(check, replacer)

    return target


# check : replacer
dict_replace = {
    'ipsum': 'XXXXXXX',
    'amet,': '***********',
    'dolor': '$$$$$'
}

new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet

print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
5

Việc sử dụng

print(s.replace('one', 'X').replace('two', 'one').replace('X', 'two'))
# two one two one two
8 giống như
print(s.replace('one', 'XtwoX').replace('two', 'YYY'))
# XYYYX YYY XYYYX YYY XYYYX

print(s.replace('two', 'YYY').replace('one', 'XtwoX'))
# XtwoX YYY XtwoX YYY XtwoX
9. Bạn có thể sử dụng phần được nhóm bởi
print(s.replace('one', 'two').replace('two', 'one'))
# one one one one one
7 hoặc chỉ định số lượng thay thế tối đa.

from re import sub
from os.path import abspath, realpath, join, dirname

file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()

new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')


def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
        # target = target.replace(check, replacer)

    return target


# check : replacer
dict_replace = {
    'ipsum': 'XXXXXXX',
    'amet,': '***********',
    'dolor': '$$$$$'
}

new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet

print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
6

Thay thế theo vị trí: Cắt lát

Không có phương pháp để thay thế chuỗi ở vị trí được chỉ định.

Bằng cách chia chuỗi bằng một lát và nối chúng với một chuỗi khác, bạn có thể tạo một chuỗi mới với vị trí được chỉ định được thay thế.

from re import sub
from os.path import abspath, realpath, join, dirname

file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()

new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')


def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
        # target = target.replace(check, replacer)

    return target


# check : replacer
dict_replace = {
    'ipsum': 'XXXXXXX',
    'amet,': '***********',
    'dolor': '$$$$$'
}

new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet

print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
7

Độ dài của chuỗi (số lượng ký tự) có thể được lấy bằng

def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = target.replace(check, replacer)

    return target
01, do đó nó có thể được viết như sau:

  • Nhận độ dài của một chuỗi (số lượng ký tự) trong Python

from re import sub
from os.path import abspath, realpath, join, dirname

file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()

new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')


def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
        # target = target.replace(check, replacer)

    return target


# check : replacer
dict_replace = {
    'ipsum': 'XXXXXXX',
    'amet,': '***********',
    'dolor': '$$$$$'
}

new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet

print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
8

Số lượng ký tự không phải khớp, vì nó chỉ nối các chuỗi khác nhau giữa các chuỗi phân chia.

from re import sub
from os.path import abspath, realpath, join, dirname

file = abspath(join(dirname(__file__), 'foo.txt'))
file_open = open(file, 'r')
file_read = file_open.read()
file_open.close()

new_file = abspath(join(dirname(__file__), 'bar.txt'))
new_file_open = open(new_file, 'w')


def replace_content(dict_replace, target):
    """Based on dict, replaces key with the value on the target."""

    for check, replacer in list(dict_replace.items()):
        target = sub(check, replacer, target)
        # target = target.replace(check, replacer)

    return target


# check : replacer
dict_replace = {
    'ipsum': 'XXXXXXX',
    'amet,': '***********',
    'dolor': '$$$$$'
}

new_content = replace_content(dict_replace, file_read)
new_file_open.write(new_content)
new_file_open.close()

# Test
print(file_read)
# Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet

print(new_content)
# Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
9

Bạn cũng có thể tạo một chuỗi mới bằng cách chèn một chuỗi khác ở bất cứ đâu trong chuỗi.

s = 'one two one two one'

print(s.replace(' ', '-'))
# one-two-one-two-one
0

Xem bài viết sau đây để biết chi tiết về cắt lát.

  • Cách cắt một danh sách, chuỗi, tuple trong Python

Bạn có thể thay thế nhiều chuỗi trong Python không?

Thay thế nhiều chuỗi con trong một chuỗi bằng cách sử dụng nhiều cuộc gọi để thay thế () được yêu cầu để thay thế nhiều chuỗi con trong một chuỗi. Ngoài ra còn có một tham số thứ ba là tùy chọn trong thay thế () chấp nhận một số nguyên để đặt số lượng thay thế tối đa để thực thi.Multiple calls to replace() function are required to replace multiple substrings in a string. There is also a third parameter that is optional in replace() which accepts an integer to set the maximum count of replacements to execute.

Làm thế nào để bạn thay thế nhiều ký tự bằng thay thế trong Python?

Thay thế nhiều ký tự trong một chuỗi bằng danh sách thay thế #..
Lưu trữ các ký tự được thay thế và thay thế trong danh sách ..
Sử dụng một vòng lặp để lặp qua danh sách ..
Sử dụng str.thay thế () phương thức để thay thế từng ký tự trong chuỗi ..

Làm thế nào để bạn thay thế nhiều yếu tố trong Python?

Phương pháp 2: Thay thế nhiều ký tự bằng cách sử dụng dịch () + maketrans () Ngoài ra, cũng có một hàm cống hiến có thể thực hiện loại tác vụ thay thế này trong một dòng do đó đây là cách được khuyến nghị để giải quyết vấn đề cụ thể này.using translate() + maketrans() There is also a dedication function that can perform this type of replacement task in a single line hence this is a recommended way to solve this particular problem.

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

Để thay thế một chuỗi trong tệp bằng Python, hãy làm theo các bước sau:..
Mở tệp đầu vào ở chế độ đọc và xử lý nó ở chế độ văn bản ..
Mở tệp đầu ra ở chế độ ghi và xử lý nó ở chế độ văn bản ..
Đối với mỗi dòng đọc từ tệp đầu vào, thay thế chuỗi và ghi vào tệp đầu ra ..
Đóng cả tệp đầu vào và đầu ra ..