我正在用Python 3写一个Discord机器人,希望将URL从http / https转换为Steam。
例如,类似
https://store.steampowered.com/app/286160/
将成为
steam://store/286160
是否有一种简单的方法可以轻松添加到其中?
答案 0 :(得分:0)
只需使用简单的split
>>> "steam://store/"+url.split("/")[-2]
>>> url = "https://store.steampowered.com/app/286160/"
>>> steam_url = "steam://store/"+url.split("/")[-2]
>>> print steam_url
steam://store/286160
>>>
答案 1 :(得分:0)
@Andrew ,您也可以尝试以下方法。
>>> inp = "https://store.steampowered.com/app/286160/"
>>>
>>> inp_url = "https://store.steampowered.com/app/286160/"
>>> arr = inp_url.split('://')
>>> arr
['https', 'store.steampowered.com/app/286160/']
>>>
>>> domain = arr[1].split('.')
>>> domain
['store', 'steampowered', 'com/app/286160/']
>>>
>>> sub_url = domain[-1].split('/')[-2]
>>> sub_url
'286160'
>>>
>>> out_url = 'stream://' + domain[0] + '/' + sub_url + '/'
>>> out_url
'stream://store/286160/'
>>>
最后,您可以设计以下函数来将实现的代码重用于url数量。
def get_modified_url(inp_url, protocol='stream'):
arr = inp_url.split('://')[1].split('.')
sub_url1 = arr[0]
sub_url2 = arr[-1].split('/')[-2]
out_url = protocol + '://' + '/'.join([sub_url1, sub_url2])
return out_url
if __name__ == '__main__':
# INPUT 1 (Use default protocol as stream)
url = 'https://store.steampowered.com/app/286160/'
output = get_modified_url(url)
print output
# INPUT 2 (Override default protocol)
url2 = 'https://store.steampowered.com/app/286560/'
output2 = get_modified_url(url2, 'new_stream')
print output2
# INPUT 3 (Override default protocol)
url3 = 'https://the_store2.steampowered.com/app/286161/'
output3 = get_modified_url(url3, 'new_stream')
print output3
stream://store/286160
new_stream://store/286560
new_stream://the_store2/286161
答案 2 :(得分:0)
您可以像这样在Python中使用re
来拆分URL。
import re
url = 'https://store.steampowered.com/app/286160/'
new_url = 'steam://store/' + re.split('/', url)[-2]
print(new_url) # output - steam://store/286160
答案 3 :(得分:0)
from urllib.parse import urlparse
url = "https://store.steampowered.com/app/286160/"
o = urlparse(url)
a = url.split(".")[0]
b = url.split("/")[-2]
c = a.replace(o.scheme,"steam")
print(c + "/" + b)