I'm new to python and I can't figure out a way to do this so I'm asking for someone to help
I have URL like this https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4 and I want to remove the last part go_cc_Jpterxvid_avi_mp4 of URL and also change /f/ with /d/ so I can get the URL to be like this https://abc.xyz/d/b
/b it change regular I have tried use somthing like this didn't work
newurl = oldurl.replace('/f/','/d/').rsplit("/", 1)[0])
Late answer, but you can use re.sub to replace "/f/.+" with "/d/b", i.e.:
old_url = "https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4"
new_url = re.sub("/f/.+", r"/d/b", old_url)
# https://abc.xyz/d/b
Regex Demo and Explanation
You can apply re.sub twice:
import re
s = 'https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4'
new_s = re.sub('(?<=\.\w{3}/)\w', 'd', re.sub('(?<=/)\w+$', '', s))
Output:
'https://abc.xyz/d/b/'
import re
domain_str = 'https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4'
#find all appearances of the first part of the url
matches = re.findall('(https?:\/\/\w*\.\w*\/?)',domain_str)
#add your domain extension to each of the results
d_extension = 'd'
altered_domains = []
for res in matches:
altered_domains.append(res + d_extension)
print(altered_domains)
exmaple input:
'https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4'
and output:
['https://abc.xyz/d']
What you had almost worked. The change is to remove the trailing right paren ) at the end of your assignment to newurl. The following works in both Python 2 and 3:
oldurl = "https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4"
newurl = oldurl.replace('/f/','/d/').rsplit("/", 1)[0]
print(newurl)
But a more idiomatic expression can be obtain thru the re standard lib:
import re
old_url = "https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4"
new_url = re.sub("/f/.+", r"/d/b", old_url)
print(new_url)
Related
I have a string like this.
'hsa:578\tup:Q16611\nhsa:578\tup:A0A0S2Z391\nhsa:9373\tup:Q9Y263\nhsa:9344\tup:Q9UL54\nhsa:5894\tup:P04049\nhsa:5894\tup:L7RRS6\nhsa:673\tup:P15056\n'
I want to get only values begin with "up:".
Like this:
up:A0A0S2Z391
up:Q9Y263
up:Q9UL54.
How can i do that with python?
By using re module for regular expressions.
import re
text = ''''hsa:578\tup:Q16611\nhsa:578\tup:A0A0S2Z391\nhsa:9373\tup:Q9Y263\nhsa:9344\tup:Q9UL54\nhsa:5894\tup:P04049\nhsa:5894\tup:L7RRS6\nhsa:673\tup:P15056\n'''
pattern = r'up:.*'
values = re.findall(pattern, text)
print(values)
Output:
['up:Q16611', 'up:A0A0S2Z391', 'up:Q9Y263', 'up:Q9UL54', 'up:P04049', 'up:L7RRS6', 'up:P15056']
You could use the split() method for that.
Here is a link to the documentation:
https://docs.python.org/3/library/stdtypes.html?#str.split
Something like this could work for the string you posted:
s = 'hsa:578\tup:Q16611\nhsa:578\tup:A0A0S2Z391\nhsa:9373\tup:Q9Y263\nhsa:9344\tup:Q9UL54\nhsa:5894\tup:P04049\nhsa:5894\tup:L7RRS6\nhsa:673\tup:P15056\n'
res = []
for i in s.split('up')[1:]:
res.append('up' + i.split()[0])
print(res)
output:
['up:Q16611', 'up:A0A0S2Z391', 'up:Q9Y263', 'up:Q9UL54', 'up:P04049', 'up:L7RRS6', 'up:P15056']
How can I split the "Value1" and "Value2 from this string?
my_str = 'Value1Value2'
I try to this but it's not work.
my_str = 'Value1Value2'
for i in my_str:
i = str(i).split('^<a.*>$|</a>')
print(i)
You can use bs4.BeautifulSoup:
from bs4 import BeautifulSoup
soup = BeautifulSoup(my_str)
out = [st.string for st in soup.find_all('a')]
Output:
['Value1', 'Value2']
One another way is to use cleaning techniques for extraction, you split on one character and remove out unwanted values.
Here's the code, I used
my_str = 'Value1Value2'
strList = my_str.split('/a>',maxsplit = 2)
for i in strList:
try:
print(i.split('>')[1].replace('<',''))
except IndexError:
pass
This will get you Value1 and Value2
If you want to do regex splitting on html, which again you shouldn’t (see bs4 answer above for way better answer).
import re
my_str = 'Value1Value2'
split_str = re.findall(r'(?<=>)\w*?(?=<\/a>)', my_str)
This works if you want the entire html element for each.
import re
re.sub("(a>)(<a)", "\\1[SEP]\\2", my_str).split("[SEP]")
if you just want the values, do this
re.findall("\>(.[^<]+)<\/a>", my_str)
here my data string :
MYDATA=DATANORMAL
MYDATA=DATA_NOTNORMAL
i use this code, but when i run it it shows empty at DATANORMAL
mydata = re.findall(r'MYDATA=(.*)' r'_.*', mystring)
print mydata
and it just shows : NOTNORMAL
i want both to work, and displays data like this:
DATANORMAL
NOTNORMAL
how do i do it? Thanks.
Try it online!
import re
mystring = """
MYDATA=DATANORMAL
MYDATA=DATA_NOTNORMAL
"""
mydata = re.findall(r'^\s*MYDATA=(?:.+_)?(.+?)\s*$', mystring, re.M)
print(mydata)
In case if you need word before _, not after, then use regex r'^\s*MYDATA=(.+?)(?:_.+)?\s*$' in code above, you may try this second variant here.
Based on what you describe, you might want to use an alternation here:
\bMYDATA=((?:DATA|(?:DATA_))\S+)\b
Script:
inp = "some text MYDATA=DATANORMAL more text MYDATA=DATA_NOTNORMAL"
mydata = re.findall(r'\bMYDATA=((?:DATA|(?:DATA_))\S+)\b', inp)
print(mydata)
This prints:
['DATANORMAL', 'DATA_NOTNORMAL']
I guess you need to add flags=re.M?
import re
mystring = """
MYDATA=DATANORMAL
MYDATA=DATA_NOTNORMAL"""
pattern = re.compile("MYDATA=(?:DATA_)?(\w+)",flags=re.M)
print(pattern.findall(mystring))
I have a URL string which is https://example.com/about/hello/
I want to split string as 'https://example.com', 'about' ,'hello'
How to do this ??
Use the urlparse to correctly parse a URL:
import urlparse
url = 'https://example.com/about/hello/'
parts = urlparse.urlparse(url)
paths = [p for p in parts.path.split('/') if p]
print 'Scheme:', parts.scheme # https
print 'Host:', parts.netloc # example.com
print 'Path:', parts.path # /about/hello/
print 'Paths:', paths # ['about', 'hello']
At the end of the day, the information you want are in the parts.scheme, parts.netloc and paths variables.
You may do this :
First split by '/'
Then join by '/' only before the 3rd occurance
Code:
text="https://example.com/about/hello/"
groups = text.split('/')
print( "/".join(groups[:3]),groups[3],groups[4])
Output:
https://example.com about hello
Inspired in Hai Vu's answer. This solution is for Python 3
from urllib.parse import urlparse
url = 'https://example.com/about/hello/'
parts = [p for p in urlparse(url).path.split('/') if p]
parts.insert(0, ''.join(url.split('/')[:3]))
There are lots of ways to do this. You could use re.split() to split on a regular expression, for instance.
>>> import re
>>> re.split(r'\b/\b', 'https://example.com/about/hello/')
['https://example.com', 'about', 'hello']
re is part of the standard library, documented here.
https://docs.python.org/3/library/re.html#re.split
The regex itself uses \b which means a boundy between a "word" character and a "non-word" character. You can use regex101 to explore how it works. https://regex101.com/r/mY8fV8/1
I need to convert spaces to %20 for api posts in a python array
tree = et.parse(os.environ['SPRINT_XML'])
olp = tree.findall(".//string")
if not olp:
print colored('FAILED', 'red') +" No jobs accociated to this view"
exit(1)
joblist = [t.text for t in olp]
How can I do that to t.text above?
I would recommend using urllib.parse module and its quote() function.
https://docs.python.org/3.6/library/urllib.parse.html#urllib.parse.quote
Example for Python3:
from urllib.parse import quote
text_encoded = quote(t.text)
Note: using quote_plus() won't work in your case as this function replaces spaces by plus char.
Use the String.replace() method as described here: http://www.tutorialspoint.com/python/string_replace.htm
So for t.text, it would be t.text.replace(" ", "%20")
Use urllib.quote_plus for this:
import urllib
...
joblist = [urllib.quote_plus(t.text) for t in olp]
Here is something I found that might help you: https://www.youtube.com/watch?v=qqxKQbKTO7o
def spaceReplace(s):
strArr = list(s)
for i, c in enumerate(strArr):
if c == ' ': strArr[i] = '%20'
return "".join(strArr)
df["Name"] = df["Name"].apply(spaceReplace)