Изменение очищенных строк (преобразовать в float и обратно) внутри списка - PullRequest
0 голосов
/ 24 мая 2018

Я тренируюсь на сайтах и ​​получаю несколько цен назад.Я не слишком знаком со списками и тем, как они работают, поэтому я не уверен, но я хочу конвертировать доллар в AUD, который составляет примерно 1: 1,32 доллара.Я бы предположил, что строка сначала eval () становится списком с плавающей точкой, а затем, возможно, просто умножается на 1,32, но я не уверен, как на самом деле сделать обмен отношениями:

from tkinter import *
from re import findall, MULTILINE

rss = open('rss.xhtml', encoding="utf8").read()

    # prints 10 price values
regex_test = findall(r'([0-9]+[.]*[0-9]*) USD', rss)
price = ["$" + regex_test for regex_test in regex_test] 
for cost in range(10):
    print(price[cost])

Это выведет10 цен, где => представляет переход к следующей цене, т. Е. 20 долларов становится 26,40 AUD:

  1. $ 20,00 => $ 26,40
  2. $ 20,00 => 26,40
  3. $ 20,00=> $ 26,40
  4. $ 20,00 => $ 26,40
  5. $ 16,00 => 21,12
  6. $ 23.50 => 31,02
  7. $ 20,00 => $ 26,40
  8. $ 16,00=> $ 21,12
  9. $ 189,00 => $ 249,48
  10. $ 16,00 => $ 21,12

В качестве вспомогательного средства, которое вытягивает цены с использованием того же регулярного выражения, здесь аналогично rssfeed https://www.etsy.com/au/shop/ElvenTechnology/rss

используется диапазон 10, так как я не хочу очищать сотни записей, только некоторые из них сверху.

Ответы [ 4 ]

0 голосов
/ 24 мая 2018

С небольшими изменениями в решении гликоаддикта в списке можно создать список обновленных цен или аналогично «переменная», из которой каждое значение из списка будет по отдельности называться:

# installs necessary modules
from tkinter import *
from re import findall, MULTILINE
import urllib.request

# downloads an rss feed to use, the feel is downloaded, 
# then saved under name and format (xhtml, html, etc.)
urllib.request.urlretrieve("https://www.etsy.com/au/shop/ElvenTechnology/rss", "rss.xhtml")
# opens the downloaded file to read from, 'U' can be used instead
# of 'encoding="utf8"', however this causes issues on some feeds, for
# example this particulare feed needs to be encoded in utf8 otherwise
# a decoding error occurs as shown below;

# return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 
# 'charmap' codec can't decode byte 0x9d in position 12605: character maps to <unidentified>


rss = open('rss.xhtml', encoding="utf8").read()
# regex is used to find all instances within the document which was opened
# and called rss
regex_test = findall(r'([0-9]+[.]*[0-9]*) USD', rss)
# formats the returned string to be modified to desired value (glycoaddict)
# aud_usd_ratio = 1.32 is the same as simply using 1.32, this just creates
# a variable with a value of 1.32 to multuply rather than simply 1.32 itself
AUD_price = ["${:.2f}".format(float(USD)*1.32) for USD in regex_test]
# loops the function 10 times, this is to stop rss feeds with thousands 
# of returns listing endlessly, this only returns the first 10, which are
# taken out of the created and formatted/modified string list, and prints
# each value individually, which is useful for say a list of label
# in tkinter to be looped and placed 
for individual_item_price in range(10):
    print(AUD_price[individual_item_price])

noteчто каждый раз, когда запускается этот файл, файл rss будет загружаться и обновляться, что означает, что его можно считать реальными ценами, если запустить его сейчас, то через час или несколько позже будут возвращаться разные результаты.

0 голосов
/ 24 мая 2018

Предположим, regex_test идентично моему prices_list_usd:

prices_list_usd = [11.11,12.22,21.324,3.11]
usd_aud_ratio = 1.32
prices_list_aud = [price*usd_aud_ratio for price in prices_list_usd]
combined_list = zip(prices_list_usd,prices_list_aud)
for pair in combined_list:
    print("$USD {0} => $AUD {1}".format(pair[0],pair[1]))
0 голосов
/ 24 мая 2018

Я думаю, вам нужно извлечь все значения, привести их к плавающей запятой и затем отформатировать соответственно

# I don't know rss file so dummy variable
rss = "$20.00 => $26.40  $20.00 => $26.40  $16.00 => $21.12  $189.00 => $249.48"

costs = re.findall(r'(?<=\$)\d+\.\d+', rss)

# cast to float and multiply with 1.32
costs = [float(cost) * 1.32 for cost in costs]

# now format them
for i in range(0, len(costs), 2):
    print("{:.2f} => {:.2f}".format(costs[i], costs[i + 1]))

# output

# 26.40 => 34.85
# 26.40 => 34.85
# 21.12 => 27.88
# 249.48 => 329.31
0 голосов
/ 24 мая 2018

Сделал ваш цикл for немного более питоническим:

from tkinter import *k    from re import findall, MULTILINE

rss = open('rss.xhtml', encoding="utf8").read()

    # prints 10 price values
regex_test = findall(r'([0-9]+[.]*[0-9]*) USD', rss)
price = ["$" + regex_test for regex_test in regex_test] 
for individual_price in price:
    print(individual_price)

для преобразования списка в AUD. Предполагая, что вы хотите просто умножить на значение, для вашего кода лучше вернуться ксписок перед добавлением знака доллара:

aud_usd_ratio = 1.32 # 1.32 AUD to 1 USD
aud_price_list = ["$" + str(float(x)*aud_usd_ratio) for x in regex_test]
print(aud_price_list)

Вы также можете использовать формат строки, если вам нужны эти два десятичных знака:

aud_price_list = ["${:.2f}".format(float(x)*aud_usd_ratio ) for x in regex_test]
print(aud_price_list)
...