0

在这段代码中,我试图获取某个用户在群聊中发布的图像的链接:

import groupy
from groupy import Bot, Group, Member

prog_group = Group.list().first
prog_members = prog_group.members()
prog_messages = prog_group.messages()
rojer = str(prog_members[4])
rojer_messages = ['none']
rojer_pics = []
links = open('rojer_pics.txt', 'w')

print(prog_group)

for message in prog_messages:
    if message.name == rojer:
        rojer_messages.append(message)
        if message.attachments:
            links.write(str(message) + '\n')

links.close()

问题是它在链接文件中打印了整个消息:(“Rojer Doewns:这是一个特殊的+https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12')>”我想要做什么,是去掉不属于 URL 的字符,所以它是这样写的:

https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12

python中有没有可以像这样操作字符串的方法?

4

3 回答 3

0
>>> string = '("Rojer Doewns: Heres a special one +https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12\')>"'
>>> string.split('+')[1][:-4]
'https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12'
于 2016-10-27T03:09:11.140 回答
0

这可以使用字符串索引和字符串方法来完成.find()

>>> url = "(\"Rojer Doewns: Heres a special one +https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12')"
>>> url = url[url.find('+')+1:-2]
>>> url
'https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12'
>>> 
于 2016-10-27T02:53:40.970 回答
0

我只是使用了 string.split() 并用括号将它分成 3 部分:

for message in prog_messages:
    if message.name == rojer:
         rojer_messages.append(message)
        if message.attachments:
            link = str(message).split("'")
            rojer_pics.append(link[1])
            links.write(str(link[1]) + '\n')
于 2016-10-27T02:33:17.177 回答