简体   繁体   English

如何从 python 中的文本中提取用户名?

[英]How to extract usernames from text in python?

So I have a message such as "Hey @richard01 what time are we meeting @freddy023?"所以我有一条消息,例如“嘿@richard01 我们什么时候见面@freddy023?” and I need a function to get it to extract the usernames which are always marked by beginning with an @ symbol.我需要一个 function 来提取始终以@符号开头的用户名。

def get_username(message, position):

So, for example, the following code would output "freddy023"因此,例如,以下代码将 output "freddy023"

get_username("Hey @richard01 what time are we meeting @freddy023?", 2)
    

You can use regex:您可以使用正则表达式:

import re

test_string = "Hey @richard01 what time are we meeting @freddy023?"

usernames = re.findall("\B@\w+", test_string)

print(usernames)
# Prints: ['@richard01', '@freddy023']

Here the regex expression matches the @ symbol followed by 1 or more word characters (including numbers).此处的正则表达式匹配@符号后跟 1 个或多个单词字符(包括数字)。 The \B makes sure the @ doesn't appear halfway through a word (like in an email) \B确保@不会出现在单词中间(如在电子邮件中)

I highly recommend having a play around with regex to fully understand how this works, Regex101 is brilliant for this.我强烈建议使用正则表达式来充分了解它是如何工作的,Regex101 非常适合这一点。 You can see this regular expression in action here: https://regex101.com/r/BOwY5z/1您可以在此处查看此正则表达式: https://regex101.com/r/BOwY5z/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM