B
B
byteDIY2018-10-18 17:15:52
Python
byteDIY, 2018-10-18 17:15:52

How to find all numbers in html file (table) and subtract 20% from each?

<tr>
<td>Установка смесителя в ванной</td>
<td>от 450 рублей</td>
</tr>
<tr>
<td>Установка смесителя на мойку, умывальник</td>
<td>от&nbsp;450 рублей</td>
</tr>

There is a table of this kind, it has more than 120 lines and it will take a lot of time to manually change each one, and the prices often change. ( For you to understand, I just support the site and add content) she must either create a new file with new rates (that is, from the existing one - 20%), or make changes to an existing one. I ask for help, just as I suppose it will require work with regular expressions, and I'm oh, how not strong in them ... Thank you.
html_file = open('table.html', 'w')

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Lisin, 2018-10-18
@byteDIY

If there are numbers in html tags and comments, they will also change. So if you have numbers there you need to change the regular expression.

import re

# Если скидку сделать отрицательной, то будет наценка 20% :)
discount = 0.2

def repl(match):
    return str(int(float(match.group(0)) * (1 - discount)))

with open('table.html', 'r+') as fd:
    new_lines = [re.sub(r'(\d+)', repl, line) for line in fd]
    fd.seek(0)
    fd.writelines(new_lines)

D
Dimonchik, 2018-10-18
@dimonchik2013

pytablereader
pytablewriter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question