python - 使用正则表达式匹配成绩单中的名称、对话和动作
问题描述
给定一个如下所示的字符串对话,我需要找到与每个用户对应的句子。
text = 'CHRIS: Hello, how are you...
PETER: Great, you? PAM: He is resting.
[PAM SHOWS THE COUCH]
[PETER IS NODDING HIS HEAD]
CHRIS: Are you ok?'
对于上述对话,我想返回包含三个元素的元组:
人名
小写的句子和
括号内的句子
像这样的东西:
('CHRIS', 'Hello, how are you...', None)
('PETER', 'Great, you?', None)
('PAM', 'He is resting', 'PAM SHOWS THE COUCH. PETER IS NODDING HIS HEAD')
('CHRIS', 'Are you ok?', None)
etc...
我正在尝试使用正则表达式来实现上述目的。到目前为止,我能够使用以下代码获取用户的姓名。我正在努力识别两个用户之间的句子。
actors = re.findall(r'\w+(?=\s*:[^/])',text)
解决方案
你可以这样做re.findall
:
>>> re.findall(r'\b(\S+):([^:\[\]]+?)\n?(\[[^:]+?\]\n?)?(?=\b\S+:|$)', text)
[('CHRIS', ' Hello, how are you...', ''),
('PETER', ' Great, you? ', ''),
('PAM',
' He is resting.',
'[PAM SHOWS THE COUCH]\n[PETER IS NODDING HIS HEAD]\n'),
('CHRIS', ' Are you ok?', '')]
您将必须弄清楚如何自己删除方括号,而在尝试匹配所有内容的同时,正则表达式无法做到这一点。
正则表达式分解
\b # Word boundary
(\S+) # First capture group, string of characters not having a space
: # Colon
( # Second capture group
[^ # Match anything that is not...
: # a colon
\[\] # or square braces
]+? # Non-greedy match
)
\n? # Optional newline
( # Third capture group
\[ # Literal opening brace
[^:]+? # Similar to above - exclude colon from match
\]
\n? # Optional newlines
)? # Third capture group is optional
(?= # Lookahead for...
\b # a word boundary, followed by
\S+ # one or more non-space chars, and
: # a colon
| # Or,
$ # EOL
)
推荐阅读
- sql - oracle sql:“获取或插入”存储过程
- python - list_filter 以选择作为值
- javascript - 我试图通过改变宽度来隐藏数组中的所有元素。在函数内部使用了 setInterval 但它只对最后一个元素正确运行
- prolog - Prolog:查找并放入列表中的重复项
- c++ - 将彩色文本绘制到 c++ win32
- java - 如何在 JAVA 中从 Azure Functions 中引用文件?
- excel - 将不同的工作表合并为具有相同结构的工作表
- c# - 在“离开”文本框后将十六进制字符串格式化为字节数组
- reactjs - HTML to JSX REACT: addEventListener to onClick
- azure - 授予 StorageV2 目录中的用户访问权限(通用 v2)