简体   繁体   English

我将如何摆脱某些字符,然后在python中输出清理后的字符串?

[英]How would I get rid of certain characters then output a cleaned up string In python?

In this snippet of code I am trying to obtain the links to images posted in a groupchat by a certain user: 在这段代码中,我试图获取特定用户在群聊中发布的图像的链接:

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()

The issue is that in the links file it prints the entire message: ("Rojer Doewns: Heres a special one +https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12')>" What I am wanting to do, is to get rid of characters that aren't part of the URL so it is written like so: 问题在于,它会在链接文件中打印整个消息:(“ Rojer Doewns:这是一个特殊的+ https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12']>“我要执行的操作,是为了删除不属于URL的字符,因此其写法如下:

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

are there any methods in python that can manipulate a string like so? python中有没有可以像这样操纵字符串的方法?

I just used string.split() and split it into 3 parts by the parentheses: 我只用了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')

This can done using string indices and the string method .find() : 这可以使用字符串索引和字符串方法.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'
>>> 
>>> 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'

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

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