Преобразуйте интервал Python в строку с обратным порядком байтов байтов

Используя значения Object #, Array # Reduce, String # replace, Map, Array # forEach, Number # toFixed и многое другое.

Эта проблема очень сложна и полностью зависит от вашей HTML-структуры. Это означает, что после того, как вы изменили свою структуру, вам нужно будет изменить код ниже.

Было бы гораздо лучше сгенерировать ваш HTML из массива объектных данных.

const data = document.querySelectorAll("tbody tr");

function stringToNumber(str){
 return Number(str.replace("€", "").trim().replace(",", "."));
}

function numberToPrice(num){
  return num.toFixed(2).replace(".", ",")
}

const res = Object
.values(data)
.reduce((a,tr)=>{
  const [name, price, quantityStr] = Object.values(tr.querySelectorAll('td'))
  .splice(1,3)
  .map(ele=>ele.textContent.replace(/(\n|\ |\t)*/g, ""));
  
  if(!name || !price || !quantityStr) return a;
  
  const quantity = stringToNumber(quantityStr);
  
  const key = `${name}|${price}`;
  //console.log(key);
  if(a.has(key)){
    const exists = a.get(key);
    exists.quantity += quantity;
    a.set(key, exists);
    tr.remove();
  } else {
    a.set(key, {tr, name, price, quantity})
  }
  return a;  
}, new Map());

[...res.values()]
.forEach(({tr, quantity, price})=>{
   const [quantityEle, totalEle] = Object.values(tr.querySelectorAll("td"))
   .splice(3,2);
   quantityEle.textContent = numberToPrice(quantity);
   totalEle.textContent = numberToPrice(quantity*stringToNumber(price)) + " €";
})
<table border="0" color="black" id="table_serv" style="font-size:10px;" width="100%">  	<thead>  		<tr>  			<th style="text-align: center;color: white;font-weight: 600;background:#BDB9B9; width:5%"></th>  			<th style="text-align: left;color: white;font-weight: 600;background:#BDB9B9;width:45%;border-right:2px solid white"><span style="font-family:verdana,geneva,sans-serif;"><span style="color:#000000;"><strong>Description</strong></span></span></th>  			<th style="text-align: center;color: white;font-weight: 600;background:#BDB9B9;width:15%;border-right:2px solid white"><span style="font-family:verdana,geneva,sans-serif;"><span style="color:#000000;"><strong>Selling Price</strong></span></span></th>  			<th style="text-align: center;color: white;font-weight: 600;background:#BDB9B9;width:15%;border-right:2px solid white"><span style="font-family:verdana,geneva,sans-serif;"><span style="color:#000000;"><strong>Quantity</strong></span></span></th>  			<th style="text-align: center;color: white;font-weight: 600;background:#BDB9B9;width:15%"><span style="font-family:verdana,geneva,sans-serif;"><span style="color:#000000;"><strong>Total</strong></span></span></th>  		</tr>  	</thead>  	<tbody>  		  		  		  		<tr>  			<td style="background:#BDB9B9;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">8</span><br>  			&nbsp;</td>  			<td style="text-align:left; border-bottom:2px solid white;border-right:2px solid white;">  			<h3 style="color: rgb(27, 155, 184); font-size: 10px; font-weight: normal; margin: 0px 0px 0.2em;">Declaration 020/2011&#8203;</h3>  			</td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">0,00 €</span></td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">1,00</span></td>  			<td style="border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;"><strong>0,00 €</strong></span></td>  		</tr>  		  		<tr>  			<td style="background:#BDB9B9;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">6</span><br>  			&nbsp;</td>  			<td style="text-align:left; border-bottom:2px solid white;border-right:2px solid white;">  			<h3 style="color: rgb(27, 155, 184); font-size: 10px; font-weight: normal; margin: 0px 0px 0.2em;">Declaration 010/2011&#8203;</h3>  			</td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">20,00 €</span></td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">1,00</span></td>  			<td style="border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;"><strong>20,00 €</strong></span></td>  		</tr>  		  		<tr>  			<td style="background:#BDB9B9;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">3</span><br>  			&nbsp;</td>  			<td style="text-align:left; border-bottom:2px solid white;border-right:2px solid white;">  			<h3 style="color: rgb(27, 155, 184); font-size: 10px; font-weight: normal; margin: 0px 0px 0.2em;">Certificate 010/2011&#8203;</h3>  			</td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">10,00 €</span></td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">1,00</span></td>  			<td style="border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;"><strong>10,00 €</strong></span></td>  		</tr>  		  		  		  		<tr>  			<td style="background:#BDB9B9;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">6</span><br>  			&nbsp;</td>  			<td style="text-align:left; border-bottom:2px solid white;border-right:2px solid white;">  			<h3 style="color: rgb(27, 155, 184); font-size: 10px; font-weight: normal; margin: 0px 0px 0.2em;">Declaration 010/2011&#8203;</h3>  			</td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">20,00 €</span></td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">1,00</span></td>  			<td style="border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;"><strong>20,00 €</strong></span></td>  		</tr>  		  		<tr>  			<td style="background:#BDB9B9;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">3</span><br>  			&nbsp;</td>  			<td style="text-align:left; border-bottom:2px solid white;border-right:2px solid white;">  			<h3 style="color: rgb(27, 155, 184); font-size: 10px; font-weight: normal; margin: 0px 0px 0.2em;">Certificate 010/2011&#8203;</h3>  			</td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">10,00 €</span></td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">1,00</span></td>  			<td style="border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;"><strong>10,00 €</strong></span></td>  		</tr>  		  		  		  		<tr>  			<td style="background:#BDB9B9;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">3</span><br>  			&nbsp;</td>  			<td style="text-align:left; border-bottom:2px solid white;border-right:2px solid white;">  			<h3 style="color: rgb(27, 155, 184); font-size: 10px; font-weight: normal; margin: 0px 0px 0.2em;">Certificate 010/2011&#8203;</h3>  			</td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">45,00 €</span></td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">1,00</span></td>  			<td style="border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;"><strong>45,00 €</strong></span></td>  		</tr>  		  		<tr>  			<td style="background:#BDB9B9;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">2</span><br>  			&nbsp;</td>  			<td style="text-align:left; border-bottom:2px solid white;border-right:2px solid white;">  			<h3 style="color: rgb(27, 155, 184); font-size: 10px; font-weight: normal; margin: 0px 0px 0.2em;">Certificate 004/2011&#8203;</h3>  			</td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">5,00 €</span></td>  			<td style="border-right:2px solid white;border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;">1,00</span></td>  			<td style="border-bottom:2px solid white"><span style="font-family:verdana,geneva,sans-serif;"><strong>5,00 €</strong></span></td>  		</tr>  		  		<tr>  			<td colspan="5" style="background:white"></td>  		</tr>  		<tr>  			<td colspan="4" style="background:white; border-bottom:1px solid #BDB9B9"><span style="font-family:verdana,geneva,sans-serif;">Sub Total</span></td>  			<td style="background:#BDB9B9;"><span style="font-family:verdana,geneva,sans-serif;">110,00 €</span></td>  		</tr>  		<tr>  			<td colspan="4" style="background:white; border-bottom:1px solid #BDB9B9"><span style="font-family:verdana,geneva,sans-serif;">Discount</span></td>  			<td style="background:#BDB9B9;"><span style="font-family:verdana,geneva,sans-serif;">0,00 €</span></td>  		</tr>  		<tr>  			<td colspan="4" style="background:white; border-bottom:1px solid #BDB9B9"><span style="font-family:verdana,geneva,sans-serif;">Total</span></td>  			<td style="background:#BDB9B9;"><span style="font-family:verdana,geneva,sans-serif;">110,00 €</span></td>  		</tr>  		<tr>  			<td colspan="4" style="background:white; border-bottom:2px solid #BDB9B9"><span style="font-family:verdana,geneva,sans-serif;">Tax 27,00%</span></td>  			<td style="background:#BDB9B9;;border-bottom:2px solid #BDB9B9"><span style="font-family:verdana,geneva,sans-serif;">29,70 €</span></td>  		</tr>  		<tr>  			<td colspan="4" style="background:white;"><strong>&nbsp;&nbsp;&nbsp;&nbsp; Grand Total</strong></td>  			<td style="background:white"><span style="font-family:verdana,geneva,sans-serif;"><span style="font-size:12px;"><strong>139,70 €</strong></span></span></td>  		</tr>  	</tbody>  </table>

56
задан Serenity 4 August 2016 в 11:45
поделиться

6 ответов

Очень легкий с pwntools, инструменты создали для программного обеспечения, взламывающего

(Неиронически, я споткнулся через этот поток и попробовал решения здесь, пока я не понял, там существует функциональность преобразования в pwntools)

import pwntools

x2 = p32(x1)
0
ответ дан 26 November 2019 в 17:15
поделиться

Вы можете использовать модуль struct :

import struct
print struct.pack('>I', your_int)

'> I' - это строка формата. > означает прямой порядок байтов, а I означает целое число без знака. Дополнительные символы формата см. В документации.

43
ответ дан 26 November 2019 в 17:15
поделиться

Это быстро и работает для малых и (произвольных) больших int:

def Dump(n): 
  s = '%x' % n
  if len(s) & 1:
    s = '0' + s
  return s.decode('hex')
print repr(Dump(1245427))  #: '\x13\x00\xf3'
13
ответ дан 26 November 2019 в 17:15
поделиться
def tost(i):
  result = []
  while i:
    result.append(chr(i&0xFF))
    i >>= 8
  result.reverse()
  return ''.join(result)
6
ответ дан 26 November 2019 в 17:15
поделиться

Вероятно, лучший способ - использовать встроенный структурный модуль :

>>> import struct
>>> x = 1245427
>>> struct.pack('>BH', x >> 16, x & 0xFFFF)
'\x13\x00\xf3'
>>> struct.pack('>L', x)[1:]  # could do it this way too
'\x13\x00\xf3'

В качестве альтернативы - и я обычно не рекомендую это, потому что это подвержено ошибкам - - вы можете сделать это «вручную» с помощью сдвига и функции chr () :

>>> x = 1245427
>>> chr((x >> 16) & 0xFF) + chr((x >> 8) & 0xFF) + chr(x & 0xFF)
'\x13\x00\xf3'

Из любопытства, почему вам нужно только три байта? Обычно вы упаковываете такое целое число в полные 32 бита (C unsigned long ) и используете struct.pack ('> L', 1245427) , но пропускаете ] [1:] шаг?

7
ответ дан 26 November 2019 в 17:15
поделиться

Использование модуля битовой строки :

>>> bitstring.BitArray(uint=1245427, length=24).bytes
'\x13\x00\xf3'

Обратите внимание, что для этого метода вам необходимо указать длину в битах создаваемой битовой строки.

Внутренне это почти то же самое, что и Ответ Алекса, но у модуля есть много дополнительных функций, если вы хотите больше работать со своими данными.

3
ответ дан 26 November 2019 в 17:15
поделиться
Другие вопросы по тегам:

Похожие вопросы: