我有一个文件,其中包含形成以下格式的单词的段 <+segment1 segment2 segment3 segment4+>
,我想要的是一个输出,其中所有段彼此相邻以形成一个单词(所以基本上我想删除段之间的空格以及段周围的 <+ +>
符号)。例如:
输入:
<+play ing+> <+game s .+>
输出:
playing games.
我首先尝试使用 \<\+(.*?)\+\>
检测模式但我似乎不知道如何删除空格
最佳答案
使用这个 Python code :
import re
line = '<+play ing+> <+game s .+>'
line = re.sub(r'<\+\s*(.*?)\s*\+>', lambda z: z.group(1).replace(" ", ""), line)
print(line)
结果:玩游戏。
lambda 还会删除空格。
正则表达式说明
--------------------------------------------------------------------------------
< '<'
--------------------------------------------------------------------------------
\+ '+'
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
\+ '+'
--------------------------------------------------------------------------------
> '>'
关于python-3.x - 正则表达式用于在 Python 中检测模式并从该模式中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70585999/