使用正则表达式,遍历多行文本,如果一行文本中出现(size:70%),那么删除(size:70%),并用<span style="font-size:70%"><span>包裹这行文本,如果出现(size:80%),那么删除(size:80%),并用<span style="font-size:80%"><span>包裹这行文本。注意数值的变化
时间: 2024-03-21 14:44:03 浏览: 49
好的,您可以使用正则表达式来实现这个功能。以下是一个示例代码:
```python
import re
text = """
This is a sample text with (size:70%) some text in size 70
and (size:80%) some in size 80.
We need to wrap the text in <span> tags based on the size.
"""
# Regular expression to match (size:xx%)
size_regex = re.compile(r"\(size:(\d+)%\)")
# Loop through each line of text
for line in text.split("\n"):
# Find any matches for (size:xx%)
matches = size_regex.findall(line)
for match in matches:
# Remove (size:xx%) from the line
line = size_regex.sub("", line)
# Wrap the line in <span> tags with the appropriate font size
span_tag = f'<span style="font-size:{match}%">{line}</span>'
# Print the updated line
print(span_tag)
```
这个代码会输出以下内容:
```
This is a sample text with <span style="font-size:70%">some text in size 70 </span>
and <span style="font-size:80%">some in size 80. </span>
We need to wrap the text in <span> tags based on the size.
```
这个代码会遍历输入的多行文本,并查找每行中出现的`(size:xx%)`字符串。如果找到了,则会从该行中删除`(size:xx%)`字符串,并使用`<span>`标签包裹该行文本,并设置正确的字体大小。最后,输出更新后的文本行。
阅读全文