@
@
@stronks2020-06-16 18:43:58
Python
@stronks, 2020-06-16 18:43:58

Is there any way to shorten the replace() method?

I am writing a VK bot that parses data. But due to VK restrictions on the length of the string in the buttons, we have to shorten the received data using the replace method .
Here is an example:

def get_content(html):
    soup = BeautifulSoup(html, 'html.parser')
    bolshaya_corobka = soup.find('div', class_='upcoming-matches')
    matches1 = []
    malencaya_corobka1 = bolshaya_corobka.find('div', class_="match-day")
    match1 = malencaya_corobka1.find_all('div', class_="upcoming-match standard-box")
    for i in match1:
        td_bo1 = i.find('td', class_="star-cell")
        if td_bo1:
            td_bo1.decompose()
        span1 = i.find('span')
        span1.decompose()
        matches1.append(i.find('table', class_="table").get_text().replace('\n\n\n', ' ').replace('\n', ' ').replace('.', ''))
    print(matches1)

Here is a small part of the replacements, the code takes 880 characters.
I saw that it is possible to replace in a string using a dictionary, but I specifically need to work with a list, are there any solutions?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
soremix, 2020-06-16
@SoreMix

In my opinion, the data from the table is taken somehow crookedly. Isn't there a separate field with the name of what you need?

S
ScriptKiddo, 2020-06-16
@ScriptKiddo

Alternatively, use this construct

source = 'St\n\n\nri\nng test\n123 ...  H.el.lo'

print(f'Before: {source}')

symbols_to_replace = {
    '\n\n\n': ' ',
    '\n': ' ',
    '.': '',
}

for search, replace in symbols_to_replace.items():
    source = source.replace(search, replace)

print(f'After: {source}')

result:
Before: St


ri
ng test
123 ...  H.el.lo
After: St ri ng test 123   Hello

D
Drill, 2020-06-16
@Drill

from re import sub
matches1.append(sub('\n+', ' ', i.find('table', class_="table").get_text()).replace('.', ''))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question