2017-08-17 145 views
0

JavaScript變量我有一個JavaScript文件Commodity.js這樣的:迭代通過使用Python

commodityInfo = [ 
["GLASS ITEM", 1.0, 1.0, ], 
["HOUSEHOLD GOODS", 3.0, 2.0, ], 
["FROZEN PRODUCTS", 1.0, 3.0, ], 
["BEDDING", 1.0, 4.0, ], 
["PERFUME", 1.0, 5.0, ], 
["HARDWARE", 5.0, 6.0, ], 
["CURTAIN", 1.0, 7.0, ], 
["CLOTHING", 24.0, 8.0, ], 
["ELECTRICAL ITEMS", 1.0, 9.0, ], 
["PLUMBING MATERIAL", 1.0, 10.0, ], 
["FLOWER", 7.0, 11.0, ], 
["PROCESSED FOODS.", 1.0, 12.0, ], 
["TILES", 1.0, 13.0, ], 
["ELECTRICAL", 9.0, 14.0, ], 
["PLUMBING", 1.0, 15.0, ] 
]; 

我想通過每一個像玻璃製品,家居用品,冷凍產品的項目進行迭代,並使用它旁邊的數一些使用Python的計算。 有人能告訴我如何打開並遍歷python中的項目。

感謝你。

+0

OP有一個** JavaScript **文件。 – randomir

+0

@randomir在我將其標記爲關閉後添加。我假設OP意味着JSON數據。 –

回答

-1

您可以使用for循環來實現。

像這樣的工作:

for commodity in commodityInfo: 
    commodity[0] # the first element (e.g: GLASS ITEM) 
    commodity[1] # the second element (e.g: 1.0) 
    print(commodity[1] + commodity[2]) #calculate two values 

您可以瞭解更多關於for循環here

+0

可以解釋downvote?作爲提到的問題'有人可以告訴我如何打開和迭代python中的項目。'它聲明'python'。 – Roshan

+0

你能告訴我如何打開文件,因爲列表是在不同的文件名CommodityDB.js中。 PS - 我沒有downvote您的評論。 – ArnabC

+0

@ArnabC你可以參考這個https://stackoverflow.com/questions/38622385/how-can-i-execute-javascript-code-from-python的第一個解決方案。這可能會有所幫助。 – Roshan

0

下面的代碼可能不是最有效的,但它適用於你的情況。

我在這裏做的是:將字符串(文件的內容)轉換爲有效的JSON,然後將JSON字符串加載到Python變量中。

注意:如果您的JS文件的內容已經是有效的JSON,會更容易!

import re 
import json 

# for the sake of this code, we will assume you can successfully load the content of your JS file 
# into a variable called "file_content" 
# E.G. with the following code: 
# 
# with open('Commodity.js', 'r') as f: #open the file 
#  file_content = f.read() 

# since I do not have such a file, I will fill the variable "manually", based on your sample data 
file_content = """ 
commodityInfo = [ 
["GLASS ITEM", 1.0, 1.0, ], 
["HOUSEHOLD GOODS", 3.0, 2.0, ], 
["FROZEN PRODUCTS", 1.0, 3.0, ], 
["BEDDING", 1.0, 4.0, ], 
["PERFUME", 1.0, 5.0, ], 
["HARDWARE", 5.0, 6.0, ], 
["CURTAIN", 1.0, 7.0, ], 
["CLOTHING", 24.0, 8.0, ], 
["ELECTRICAL ITEMS", 1.0, 9.0, ], 
["PLUMBING MATERIAL", 1.0, 10.0, ], 
["FLOWER", 7.0, 11.0, ], 
["PROCESSED FOODS.", 1.0, 12.0, ], 
["TILES", 1.0, 13.0, ], 
["ELECTRICAL", 9.0, 14.0, ], 
["PLUMBING", 1.0, 15.0, ] 
]; 
""" 

# get rid of leading/trailing line breaks 
file_content = file_content.strip() 

# get rid of "commodityInfo = " and the ";" and make the array valid JSON 
r = re.match(".*=", file_content) 
json_str = file_content.replace(r.group(), "").replace(";", "").replace(", ]", "]") 

# now we can load the JSON into a Python variable 
# in this case, it will be a list of lists, just as the source is an array of array 
l = json.loads(json_str) 

# now we can do whatever we want with the list, e.g. iterate it 
for item in l: 
    print(item)