Python 正则表达式将单行转换为多行

问题描述 投票:0回答:2

这是我的单行数据。

1. B 2. E 3. E 4. D 5. E 6. A 7. A 8. E 9. E 10. D

如何使用python转换成多行如下

1. B
2. E
3. E
.
.
10. D
python python-3.x regex
2个回答
0
投票

您确实可以使用正则表达式来实现此目的。

此 python 代码使用正则表达式将字符串转换为所需的多行格式:

import re

my_string: str = "1. B 2. E 3. E 4. D 5. E 6. A 7. A 8. E 9. E 10. D"
# Use regex to find all occurrences of the pattern "number. letter"
matches = re.findall(r'\d+\.\s\w', data)
# Join the matches with newline characters; this creates the multi-lines
formatted_data = "\n".join(matches)

# Print the formatted data
print(formatted_data)

我使用

re.findall
查找特定模式的所有出现,然后将它们与换行符
\n
连接起来以创建多行支持。


0
投票

除了用

\n
替换每个 EOL 之外,您还可以尝试这种方法,该方法采用由数字、点和字母组成的每个元素并按顺序打印它们:

import re

line = "1. B 2. E 3. E 4. D 5. E 6. A 7. A 8. E 9. E 10. D"

entries = re.findall(r'\d+\.\s[A-Z]', line)

for entry in entries:
    print(entry)

这是您应该得到的输出:

1. B
2. E
3. E
4. D
5. E
6. A
7. A
8. E
9. E
10. D
© www.soinside.com 2019 - 2024. All rights reserved.