假设这个字符串:
[aaa ] some text here [bbbb3 ] some other text here [cc ] more text
我想使用这样的键值对:
Key Value
aaa some text here
bbbb3 some other text here
cc more text
或者像这样的 pandas DataFrame
aaa | bbbb3 |cc
-------------------------------------------------
some text here | some other text here | more text
next line | ..... | .....
我试过像这样的正则表达式:r'\[(.{6})\]\s(.*?)\s\[' 但这不起作用。
请您参考如下方法:
使用re.findall,将感兴趣的区域提取到列中。然后,您可以根据需要删除空格。
既然您提到您愿意将其读入 DataFrame,那么您可以将这项工作留给 pandas。
import re
matches = re.findall(r'\[(.*?)\](.*?)(?=\[|$)', text)
df = (pd.DataFrame(matches, columns=['Key', 'Value'])
.apply(lambda x: x.str.strip()))
df
Key Value
0 aaa some text here
1 bbbb3 some other text here
2 cc more text
或者(回复:编辑),
df = (pd.DataFrame(matches, columns=['Key', 'Value'])
.apply(lambda x: x.str.strip())
.set_index('Key')
.transpose())
Key aaa bbbb3 cc
Value some text here some other text here more text
模式匹配大括号内的文本,然后是大括号外的文本,直到下一个左大括号。
\[ # Opening square brace
(.*?) # First capture group
\] # Closing brace
(.*?) # Second capture group
(?= # Look-ahead
\[ # Next brace,
| # Or,
$ # EOL
)
