2015-05-20 28 views
0

我有包含在以下格式的數據文件discount.txt將其存儲在一個列表:解析文本文件和

Less than $100 --> 0% 
From $100 up to less than $500 --> 10% 
From $500 up to less than $1,000 --> $40 PLUS 20% 
From $1,000 up to less than $2,000 --> $140 PLUS 30% 
$2,000 and above --> $440 PLUS 40% 

這意味着在銷售金額

Less than $100 0% 
From $100 up to less than $500 10% for each dollar over $100 
From $500 up to less than $1,000 $40 PLUS 20% of the total sale amount over $500 
From $1,000 up to less than $2,000 $140 PLUS 30% of the total sale amount over $1,000 
$2,000 and above $440 PLUS 40% of the total sale amount over $2,000 

也就是說折扣,如果總銷售額爲100美元,那麼折扣將爲0美元。但是,如果總銷售額爲$ 101,則折扣將爲$ 0.10。如果總銷售額爲500美元,則折扣將爲40美元,但如果總銷售額爲501美元,則折扣將爲40.20美元。

爲了解決這個問題,我認爲有4個清單:1個用於存儲銷售額下限的清單,1個用於上限的清單,1個用於存放與範圍相對應的固定增量的清單,以及一個用於存放額外打折的清單。如果沒有固定增量,則將其假設爲零。

那麼對於給定的銷售額,如果它位於第i範圍內,那麼只是這樣做:

fixedIncrement[i] + (saleAmount-lowerLimit[i])*additionDiscount[i] 

但是問題現在面臨被解析給定的文本文件。是否有人可以幫助解析它,它

這裏存放在列出蟒蛇在給定的文件列表會是這樣的:

lowerLimit[] = [1,100,500,1000,2000] 
upperLimit[] = [100,500,1000,2000,MAX] 
fixedIncrement[] = [0,0,40,140,440] 
additionDiscount[] = [0,0.1,0.2,0.3,0.4] 
+0

@Prera​​kSola我解釋我的做法。我想知道除了我在想什麼之外是否還有更好的替代方案。我的代碼有點混亂。我採取了每條線並解析它。我希望有一些優雅的方式來做到這一點 – ms8

+1

你解釋了你的計算方法。但是你提到的問題是解析文本文件。那麼到目前爲止,您嘗試解析該文本文件的是什麼?那麼錯誤/不需要的行爲是什麼? –

+0

@python_slayer最有可能的方法將是相同的:你取一行,正則表達式的值並將它們存儲在列表列表中。然後,從初始列表中的每個列表的i ++元素創建列表的新列表。 – konart

回答

0

要打開一個.txt:

with open ("data.txt", "r") as myfile: 
    data=myfile.readlines() 

每行應是在列表的字符串例如[ '串一個',線二'] 每個字符串轉換爲字符串列表

all_lines = [i.split() for i in data] 
>>> all_lines = [['string', 'one'], ['string', 'two']] 

for l in all_lines: 
    # Go through each line 

從$ 100達不到$ 500 - > 10%轉化爲:

l = ['From', '$100', 'up', 'to', 'less', 'than', '$500', '-->', '10%'] 

現在你應該能夠使用邏輯來解析它。例如獲得的參數範圍內這一行的:

all_ranges = [] 
r1 = [i for i in l if "$" in i] 
if l[0] == 'From': # Contains a range  
    r = (int(r1[0][1:]), int(r1[1][1:])) 
    all_ranges.append(r) 

print all_ranges 

>>> [(100, 500)] 

編輯:

elif l[0] == "Less": # No range in this line 
    r = (0, int(r1[0][1:])) # Range is from 0 to $100 
    all_ranges.append(r) 
else: 
    top = l[0][1:] 
    all_ranges.append((top, 1000000)) # High range 

>>>> [(100, 500), (0, 100), (2000, 1000000)] 
+0

那些不包含'From'的行呢?您能否請全文解釋文本?像第一行一樣少於100美元,最好包含範圍(1,100)。同樣的最後一行upto最大限制 – ms8

+0

最後一個疑問,如何加載文本文件爲csv字符串? – ms8

+0

使用類似reader = csv.reader(csvfile,delimiter ='')的東西。請參閱http://stackoverflow.com/questions/17262256/reading-one-line-of-csv-data-in-python – kezzos

0

你可以按照這個方法:

  1. 創建您的數據的CSV文件。這將降低閱讀文件的複雜性。該格式可以是這樣的:

LOWER_LIMIT,UPPER_LIMIT,fixed_increment,折扣
1,100,0,0
100,500,0,0.1
500,1000,40,0.2

  1. 使用python的csv模塊讀取文件並將值存儲在相應的列表中。你可以在這裏看到關於它的文件:Python docs
  2. 根據你的公式計算金額。
+0

我不想製作單獨的文件。我可以修改我的數據結構,但沒有其他文件。我必須使用正則表達式和所有的解析它 – ms8

+0

@python_slayer所以你在一個類中這樣做。 –

+0

@Prera​​ksola在課堂上? – ms8