2024-02-02 12:03:44 +00:00
|
|
|
|
import re
|
|
|
|
|
from difflib import ndiff
|
|
|
|
|
|
|
|
|
|
|
2025-06-01 23:56:11 +00:00
|
|
|
|
def get_diff(original: str, modified: str) -> list[str]:
|
2024-02-02 12:03:44 +00:00
|
|
|
|
"""
|
|
|
|
|
Get the difference between two strings using difflib.
|
|
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
|
- original: The original string.
|
|
|
|
|
- modified: The modified string.
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
A list of differences.
|
|
|
|
|
"""
|
2025-06-01 23:56:11 +00:00
|
|
|
|
return list(ndiff(original.split(), modified.split()))
|
2024-02-02 12:03:44 +00:00
|
|
|
|
|
2024-02-02 12:59:22 +00:00
|
|
|
|
|
2025-06-01 23:56:11 +00:00
|
|
|
|
def apply_diff(original: str, diff: list[str]) -> str:
|
2024-02-02 12:03:44 +00:00
|
|
|
|
"""
|
|
|
|
|
Apply the difference to the original string.
|
|
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
|
- original: The original string.
|
|
|
|
|
- diff: The difference obtained from get_diff function.
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
The modified string.
|
|
|
|
|
"""
|
2024-04-17 15:32:23 +00:00
|
|
|
|
pattern = re.compile(r"^(\+|-) ")
|
2024-02-02 12:03:44 +00:00
|
|
|
|
|
2025-07-02 19:30:21 +00:00
|
|
|
|
# Используем list comprehension вместо цикла с append
|
|
|
|
|
result = []
|
2024-02-02 12:03:44 +00:00
|
|
|
|
for line in diff:
|
|
|
|
|
match = pattern.match(line)
|
|
|
|
|
if match:
|
|
|
|
|
op = match.group(1)
|
2024-04-17 15:32:23 +00:00
|
|
|
|
if op == "+":
|
2025-07-02 19:30:21 +00:00
|
|
|
|
result.append(line[2:]) # content
|
|
|
|
|
# Игнорируем удаленные строки (op == "-")
|
2024-02-02 12:03:44 +00:00
|
|
|
|
else:
|
|
|
|
|
result.append(line)
|
|
|
|
|
|
2024-04-17 15:32:23 +00:00
|
|
|
|
return " ".join(result)
|