python - 推特用户名的正则表达式,但某些匹配指定格式 - Python
问题描述
我是正则表达式的新手。我目前正在尝试用@MENTION 替换推文中的所有用户名,除了我之前已经更改为@CEO、@COMPANY 和@MEDIA 的用户名。
最终的解决方案应该是这样的:最初的推文:“@John 被@COMPANY 告知他不会收到他的奖金,@MEDIA 报道。” 最后一条推文:“@MEDIA 报道,@COMPANY 告诉@MENTION 他不会收到奖金。”
我尝试了不同的版本,但无法解决它们。如果您能提供帮助,将不胜感激。
这是一次尝试,我让它做的与我想要的相反,但我无法解决它。
pattern = re.compile("@(MEDIA)|(CEO)|(EMPLOYEE)")
test = ["hello @CEO said the @user in the @MEDIA", "there is a new @EMPLOYEE said the @user"]
for t in test:
test = [re.sub(pattern,"USER",t) for t in test]
test
>>>['hello @USER said the @user in the USER', 'there is a new @USER said the @user']
解决方案
您可以使用
(?<!\S)@(?!COMPANY|CEO|MEDIA)\b[^@\s]+
模式匹配:
(?<!\S)@
在左边断言一个空白边界,然后匹配@(?!COMPANY|CEO|MEDIA)\b
负前瞻,不直接断言任何替代方案的权利[^@\s]+
匹配除 @ 或 whitspace 字符之外的任何字符的 1 次以上。
在替换中,您可以使用"@MENTION"
import re
pattern = re.compile(r"(?<!\S)@(?!COMPANY|CEO|MEDIA)\b[^@\s]+")
test = ["hello @CEO said the @user in the @MEDIA", "there is a new @EMPLOYEE said the @user"]
for t in test:
test = re.sub(pattern, "@MENTION", t)
print(test)
输出
hello @CEO said the @MENTION in the @MEDIA
there is a new @MENTION said the @MENTION
推荐阅读
- python - ValueError:查看限制最小值 -0.5 小于 1,并且在绘制到条形图时是无效的 Matplotlib 日期值
- python - Python,将 n x m numpy 数组与 n 大小的 numpy 数组进行比较
- php - Laravel 5.7:如何使用多个框发送联系表
- c# - 字体 Aharoni 不支持常规样式
- php - 如何从无法安装任何东西的服务器发送电子邮件?
- c# - 有人可以向我解释一下这个 Chunk Size 值吗
- sql - BigQuery 标准 SQL:将值设置为正无穷或负无穷
- java - 未调用 Rest Controller 中的获取服务
- java - Java链表指针垃圾回收
- ios - 在 Metal 中从 IOSurface 获取纹理