Hướng dẫn how do you replace multiple items in a string in python? - làm thế nào để bạn thay thế nhiều mục trong một chuỗi trong python?

Tôi cần một giải pháp trong đó các chuỗi được thay thế có thể là một biểu thức thông thường, ví dụ để giúp bình thường hóa một văn bản dài bằng cách thay thế nhiều ký tự khoảng trắng bằng một ký tự duy nhất. Dựa trên một chuỗi câu trả lời từ những người khác, bao gồm Miniquark và MMJ, đây là những gì tôi đã nghĩ ra:

def multiple_replace[string, reps, re_flags = 0]:
    """ Transforms string, replacing keys from re_str_dict with values.
    reps: dictionary, or list of key-value pairs [to enforce ordering;
          earlier items have higher priority].
          Keys are used as regular expressions.
    re_flags: interpretation of regular expressions, such as re.DOTALL
    """
    if isinstance[reps, dict]:
        reps = reps.items[]
    pattern = re.compile["|".join["[?P%s]" % [i, re_str[0]]
                                  for i, re_str in enumerate[reps]],
                         re_flags]
    return pattern.sub[lambda x: reps[int[x.lastgroup[1:]]][1], string]

Nó hoạt động cho các ví dụ được đưa ra trong các câu trả lời khác, ví dụ:

>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'

Điều chính đối với tôi là bạn cũng có thể sử dụng các biểu thức thông thường, ví dụ, chỉ để thay thế toàn bộ từ hoặc để bình thường hóa không gian trắng:

>>> s = "I don't want to change this name:\n  Philip II of Spain"
>>> re_str_dict = {r'\bI\b': 'You', r'[\n\t ]+': ' '}
>>> multiple_replace[s, re_str_dict]
"You don't want to change this name: Philip II of Spain"

Nếu bạn muốn sử dụng các phím từ điển làm chuỗi bình thường, bạn có thể thoát khỏi chúng trước khi gọi nhiều_replace bằng ví dụ: Chức năng này:

def escape_keys[d]:
    """ transform dictionary d by applying re.escape to the keys """
    return dict[[re.escape[k], v] for k, v in d.items[]]

>>> multiple_replace[s, escape_keys[re_str_dict]]
"I don't want to change this name:\n  Philip II of Spain"

Chức năng sau đây có thể giúp tìm các biểu thức chính quy sai lầm trong số các khóa từ điển của bạn [vì thông báo lỗi từ nhiều_replace không nói lắm]:

def check_re_list[re_list]:
    """ Checks if each regular expression in list is well-formed. """
    for i, e in enumerate[re_list]:
        try:
            re.compile[e]
        except [TypeError, re.error]:
            print["Invalid regular expression string "
                  "at position {}: '{}'".format[i, e]]

>>> check_re_list[re_str_dict.keys[]]

Lưu ý rằng nó không chuỗi thay thế, thay vào đó thực hiện chúng đồng thời. Điều này làm cho nó hiệu quả hơn mà không hạn chế những gì nó có thể làm. Để bắt chước ảnh hưởng của chuỗi, bạn có thể chỉ cần thêm nhiều cặp thay thế chuỗi và đảm bảo thứ tự dự kiến ​​của các cặp:

>>> multiple_replace["button", {"but": "mut", "mutton": "lamb"}]
'mutton'
>>> multiple_replace["button", [["button", "lamb"],
...                             ["but", "mut"], ["mutton", "lamb"]]]
'lamb'

Trong bài viết này, chúng tôi sẽ học cách chuyển đổi một danh sách thành một chuỗi 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. Trước tiên chúng ta hãy xem nhanh danh sách và chuỗi trong Python.

Chuỗi Python

Chuỗi là một loại trong ngôn ngữ python giống như số nguyên, float, boolean, v.v ... Dữ liệu được bao quanh bởi các trích dẫn đơn hoặc trích dẫn kép được cho là một chuỗi. Một chuỗi còn được gọi là một chuỗi các ký tự.

string1 = "apple"
string2 = "Preeti125"
string3 = "12345"
string4 = "Model number is 56@1"

Thay thế nhiều chuỗi con trong chuỗi bằng cách sử dụng thay thế []

Ví dụ dưới đây sử dụng hàm

>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
2 được cung cấp bởi các chuỗi Python. Nó thay thế tất cả các lần xuất hiện của chuỗi phụ cho một chuỗi mới bằng cách chuyển các chuỗi cũ và mới làm tham số cho hàm
>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
2. Nhiều cuộc gọi đến chức năng
>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
2 đượ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
>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
2, chấp nhận một số nguyên để đặt số lượng thay thế tối đa để thực thi.

ví dụ 1

str1 = "Fear leads to anger; anger leads to hatred; hatred leads to conflict"

str2 = str1.replace["anger", "rage"]
str3 = str2.replace["to", "2"]

print[str3]


Nỗi sợ hãi dẫn đến 2 cơn thịnh nộ; Rage dẫn 2 thù hận; Hận thù dẫn đầu 2 Xung đột

Ví dụ: Tạo từ điển của các chuỗi con để thay thế

Các ví dụ dưới đây tạo ra một từ điển của các chuỗi con như các cặp giá trị khóa. Các khóa đại diện cho chuỗi phụ và giá trị là các chuỗi mới.

str1 = "Fear leads to anger; anger leads to hatred; hatred leads to conflict"

char_to_replace = {'to': '2', ';': ',', 'anger': 'rage'}

# Iterate over all key-value pairs in dictionary 
for key, value in char_to_replace.items[]:
    # Replace key character with value character in string
    str1 = str1.replace[key, value]

print[str1]


Nỗi sợ hãi dẫn đến 2 cơn thịnh nộ, cơn thịnh nộ dẫn đến sự thù hận 2, hận thù dẫn đầu 2 Xung đột

Thí dụ

Phương pháp này sử dụng hai chức năng -

>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
6 và
>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
7.

>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
7 - Nó là một bảng ánh xạ giữa chuỗi ban đầu và sự thay thế của nó. Nó là một phương pháp của str. Phải mất hai tham số - một chuỗi cũ và một chuỗi mới.

>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
6 - Nó tạo ra chuỗi được dịch được thử lại bởi hàm
>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
7.

import string

str1 = "Fear leads to anger; anger leads to hatred; hatred leads to conflict"

res = str1.translate[str.maketrans["o", "0"]]
print[res]


Nỗi sợ hãi dẫn đến sự tức giận T0; sự tức giận dẫn đến sự thù hận T0; Hận thù dẫn đầu T0 C0nflict

Ví dụ: Thay thế bằng mô -đun Regex

Phương pháp này sử dụng mô -đun của

>>> s = "I don't want to change this name:\n  Philip II of Spain"
>>> re_str_dict = {r'\bI\b': 'You', r'[\n\t ]+': ' '}
>>> multiple_replace[s, re_str_dict]
"You don't want to change this name: Philip II of Spain"
1 Python. Regex cung cấp nhiều hoạt động chuỗi dựa trên các biểu thức. Chúng tôi sẽ sử dụng hai chức năng của mô-đun Regex-
>>> s = "I don't want to change this name:\n  Philip II of Spain"
>>> re_str_dict = {r'\bI\b': 'You', r'[\n\t ]+': ' '}
>>> multiple_replace[s, re_str_dict]
"You don't want to change this name: Philip II of Spain"
2 và
>>> s = "I don't want to change this name:\n  Philip II of Spain"
>>> re_str_dict = {r'\bI\b': 'You', r'[\n\t ]+': ' '}
>>> multiple_replace[s, re_str_dict]
"You don't want to change this name: Philip II of Spain"
3 để thay thế nhiều chuỗi con trong một chuỗi.

>>> s = "I don't want to change this name:\n  Philip II of Spain"
>>> re_str_dict = {r'\bI\b': 'You', r'[\n\t ]+': ' '}
>>> multiple_replace[s, re_str_dict]
"You don't want to change this name: Philip II of Spain"
4 - Nó thay thế nội dung của một chuỗi dựa trên các mẫu. Nó lấy một mẫu hoặc một chuỗi làm đối số đầu tiên. Đối số thứ hai là hàm LambDA trích xuất chuỗi con phù hợp sau đó trả về giá trị được liên kết với nó từ từ điển. Nó lấy chuỗi ban đầu làm đối số thứ ba.

>>> s = "I don't want to change this name:\n  Philip II of Spain"
>>> re_str_dict = {r'\bI\b': 'You', r'[\n\t ]+': ' '}
>>> multiple_replace[s, re_str_dict]
"You don't want to change this name: Philip II of Spain"
5 - Nó tương tự như hàm trên nhưng nó trả về một bộ của chuỗi được chuyển đổi và số lượng thay thế được thực hiện. Nó rất hữu ích nếu bạn muốn lưu ý có bao nhiêu nhóm mẫu bạn thao tác như số liệu hoặc để xử lý thêm.

Ví dụ 1 Sử dụng Re.Sub []

Khi

>>> s = "I don't want to change this name:\n  Philip II of Spain"
>>> re_str_dict = {r'\bI\b': 'You', r'[\n\t ]+': ' '}
>>> multiple_replace[s, re_str_dict]
"You don't want to change this name: Philip II of Spain"
2 khớp với mẫu từ chuỗi, nó gọi hàm Lambda, cung cấp ký tự thay thế, sau đó hàm
>>> s = "I don't want to change this name:\n  Philip II of Spain"
>>> re_str_dict = {r'\bI\b': 'You', r'[\n\t ]+': ' '}
>>> multiple_replace[s, re_str_dict]
"You don't want to change this name: Philip II of Spain"
4 thay thế ký tự đó trong chuỗi.

>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
0


Sợ x giận dữ; tức giận x đến sự thù hận; Lòng thù hận x xung đột

Ví dụ: Sử dụng re.subn []

>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
1


Xin chào, số của tôi là xxxxxxx. Tôi là xx tuổi. Tôi sống ở phố XXXB Baker.

Sự kết luận

Trong bài viết này, chúng tôi đã học cách thay thế nhiều chuỗi con trong một chuỗi bằng cách sử dụng một số chức năng tích hợp như

>>> s = "I don't want to change this name:\n  Philip II of Spain"
>>> re_str_dict = {r'\bI\b': 'You', r'[\n\t ]+': ' '}
>>> multiple_replace[s, re_str_dict]
"You don't want to change this name: Philip II of Spain"
2,
>>> s = "I don't want to change this name:\n  Philip II of Spain"
>>> re_str_dict = {r'\bI\b': 'You', r'[\n\t ]+': ' '}
>>> multiple_replace[s, re_str_dict]
"You don't want to change this name: Philip II of Spain"
3,
def escape_keys[d]:
    """ transform dictionary d by applying re.escape to the keys """
    return dict[[re.escape[k], v] for k, v in d.items[]]

>>> multiple_replace[s, escape_keys[re_str_dict]]
"I don't want to change this name:\n  Philip II of Spain"
0,
def escape_keys[d]:
    """ transform dictionary d by applying re.escape to the keys """
    return dict[[re.escape[k], v] for k, v in d.items[]]

>>> multiple_replace[s, escape_keys[re_str_dict]]
"I don't want to change this name:\n  Philip II of Spain"
1,
>>> multiple_replace["[condition1] and --condition2--",
...                  {"condition1": "", "condition2": "text"}]
'[] and --text--'

>>> multiple_replace['hello, world', {'hello' : 'goodbye', 'world' : 'earth'}]
'goodbye, earth'

>>> multiple_replace["Do you like cafe? No, I prefer tea.",
...                  {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'}]
'Do you prefer tea? No, I prefer cafe.'
6 và chúng tôi cũng đã sử dụng một số mã tùy chỉnh.

Bài Viết Liên Quan

Chủ Đề