tkt*_*711 2 python regex twitter text
有一个列表字符串twitter文本数据,例如,以下数据(实际上,有大量文本,而不仅仅是这些数据),我想在Twitter文本中提取@和url链接后的所有用户名,例如:galaxy5univ和url链接.
tweet_text = ['@galaxy5univ I like you',
'RT @BestOfGalaxies: Let's sit under the stars ...',
'@jonghyun__bot .........((thanks)',
'RT @yosizo: thanks.ddddd <https://yahoo.com>',
'RT @LDH_3_yui: #fam, ccccc https://msn.news.com']
Run Code Online (Sandbox Code Playgroud)
我的代码:
import re
pu = re.compile(r'http\S+')
pn = re.compile(r'@(\S+)')
for row in twitter_text:
text = pu.findall(row)
name = (pn.findall(row))
print("url: ", text)
print("name: ", name)
Run Code Online (Sandbox Code Playgroud)
通过测试大量twitter数据中的代码,我得到了我的两个url和name模式都是错误的(尽管在一些twitter文本数据中是正确的).在大型Twitter数据的情况下,你们是否有一些关于提取名称和url的文件或链接来自twitter文本.
如果您有关于从Twitter数据中提取名称和URL的建议,请告诉我,谢谢!
请注意,您的pn = re.compile(r'@(\S+)')正则表达式将捕获任何1个以上的非空格字符@.
要排除匹配:,您需要将速记\S类转换为[^\s]等效的否定字符类,并添加:到它:
pn = re.compile(r'@([^\s:]+)')
Run Code Online (Sandbox Code Playgroud)
现在,它将在第一个之前停止捕获非空白符号:.请参阅正则表达式演示.
如果你需要捕获到最后一个:,你可以:在捕获组之后添加:pn = re.compile(r'@(\S+):').
对于URL匹配正则表达式,Web上有很多,只需选择最适合您的那个.
这是一个示例代码:
import re
p = re.compile(r'@([^\s:]+)')
test_str = "@galaxy5univ I like you\nRT @BestOfGalaxies: Let's sit under the stars ...\n@jonghyun__bot .........((thanks)\nRT @yosizo: thanks.ddddd <https://y...content-available-to-author-only...o.com>\nRT @LDH_3_yui: #fam, ccccc https://m...content-available-to-author-only...s.com"
print(p.findall(test_str))
p2 = re.compile(r'(?:http|ftp|https)://(?:[\w_-]+(?:(?:\.[\w_-]+)+))(?:[\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?')
print(p2.findall(test_str))
# => ['galaxy5univ', 'BestOfGalaxies', 'jonghyun__bot', 'yosizo', 'LDH_3_yui']
# => ['https://yahoo.com', 'https://msn.news.com']
Run Code Online (Sandbox Code Playgroud)