【问题标题】:How to iterate over a file and put the all the id values into an list [Python]如何遍历文件并将所有 id 值放入列表 [Python]
【发布时间】:2018-05-07 21:43:51
【问题描述】:
{'asin': '0756029929', 'description': 'Spanish Third-year Pin, 1 inch in diameter.  Set of 10.', 'title': 'Spanish Third-year Pin Set of 10', 'price': 11.45, 'imUrl': 'http://ecx.images-amazon.com/images/I/51AqSOl7qLL._SY300_.jpg', 'salesRank': {'Toys & Games': 918374}, 'categories': [['Clothing, Shoes & Jewelry', 'Novelty, Costumes & More', 'Novelty', 'Clothing']]}
{'asin': '0756029104', 'description': 'Viva Espaol pin, 1 x 1 inch. Set of 10.', 'title': 'Viva Espanol Pins Set of 10', 'price': 11.45, 'imUrl': 'http://ecx.images-amazon.com/images/I/51By%2BZpF9DL._SY300_.jpg', 'salesRank': {'Home & Kitchen': 2651070}, 'categories': [['Clothing, Shoes & Jewelry', 'Novelty, Costumes & More', 'Novelty', 'Clothing']]}
{'asin': '0839933363', 'description': 'This necklace from the popular manga and anime series, Death Note. The necklace\'s charm is black and silver with the text, "Death Note" upon it. The approx. length of the necklace is 12"Dimension & Measurement:Length: Approx. 12"', 'title': 'Death Note Anime Manga: Cross Logo necklace', 'imUrl': 'http://ecx.images-amazon.com/images/I/51f0HkHssyL._SY300_.jpg', 'salesRank': {'Toys & Games': 1350779}, 'categories': [['Clothing, Shoes & Jewelry', 'Novelty, Costumes & More', 'Costumes & Accessories']]}
{'asin': '1304567583', 'description': 'pink bikini swimwear glow in the dark fashion', 'title': 'Pink Bikini Swimwear Glow in the Dark Fashion', 'price': 19.99, 'imUrl': 'http://ecx.images-amazon.com/images/I/41pS%2B98jhlL._SY300_.jpg', 'categories': [['Clothing, Shoes & Jewelry', 'Novelty, Costumes & More', 'Costumes & Accessories', 'Costumes']]}
{'asin': '1304567613', 'description': 'Bikini Swimwear glow in the dark fashion blue', 'title': 'Bikini Swimwear Blue Glow in the Dark Fashion', 'price': 29.99, 'imUrl': 'http://ecx.images-amazon.com/images/I/41ZNIUvYkyL._SY300_.jpg', 'categories': [['Clothing, Shoes & Jewelry', 'Novelty, Costumes & More', 'Costumes & Accessories', 'Costumes']]}
{'asin': '1465014578', 'title': '2013 Desk Pad Calendar', 'imUrl': 'http://ecx.images-amazon.com/images/I/51NadiHHHsL._SX342_.jpg', 'related': {'also_bought': ['B009SDBX0Q', 'B009DCUY1G'], 'bought_together': ['B009SDBX0Q', 'B009DCUY1G']}, 'salesRank': {'Clothing': 505645}, 'categories': [['Clothing, Shoes & Jewelry', 'Novelty, Costumes & More', 'Band & Music Fan', 'Accessories']]}
{'asin': '1620574128', 'related': {'also_bought': ['B0015KET88', 'B00004WKPP', 'B000F8T8U0', 'B000F8V736', 'B000F8VAOM', 'B0015KGFQM', 'B003U6P4OS', '1564519392', 'B000F8XF8Q', 'B0042SR3E2', 'B004PBLVDU', 'B000G3LR9Y', 'B0006PKZBI', 'B0007PC9CK', 'B001G98DS0', 'B001UFWJLW', 'B003S8XLWA', '0486214834', '1609964713', 'B000P1PVMQ', '0590308572', 'B000QDZY52', '1564514188', 'B0006PKZ7W', 'B000T2YKIM', 'B000QDTWF0', 'B000FA6DXS', 'B0007P94ZA', 'B000WA3FKU', 'B00004WKPU', 'B000F8XF68', 'B004DJ51JE', '

我有这个文件,想把 asins 的所有值放到自己的列表中,这是我目前所拥有的,但我不知道该怎么做或者最好的方法是什么,因为该文件具有 .json 的扩展名,但它不是 vaild json 的格式,因此我为什么要像普通文本文件一样尝试这样做。

with open('File.json', "r") as f:
    for line in f:
         if 'asin' in line:
        #Code that gets the values of asins
         clothing_ids.append(#then add them values to clothing_ids)

print(clothing_ids)

【问题讨论】:

  • 您可能想查看一个实际的 JSON 解析器。
  • @MadPhysicist 但是当我尝试这个时,由于文件的结构,我只是得到一个错误,它抱怨它不是有效的 json

标签: python arrays json data-analysis


【解决方案1】:

ast.literal_eval使用列表推导:

import ast
data = ast.literal_eval(open('File.json').read())
asins = [i['asin'] for i in data]

【讨论】:

  • 当我尝试使用这个时,我得到一个无效的语法错误。
  • 文件“”,第 2 行 {'asin': '0681256036', 'related': {'also_viewed': ['B005TLMG0M', 'B002R0DRR4', 'B005VQ0NBY', 'B001G5ZCBA ','b00.ai7vztk','b0069s2dkw','b005tkze1q','b001g5zcc4','b002r0dosq','b001pmuupc','b005tl3rm8','b005tlnete','b005tlnete','b009o0h11i','b002c0h11i','b002c0f3rq','b00avqwcqi','b001hx4mcg','b001hx4mcg', 'B00FF0VCAW', 'B00946ZOT8', 'B002WGHXI2']}, 'title': 'Twilight Saga: New Moon Alice Chocker Necklace Wearable Prop Replica', 'price': 17.59, 'salesRank': {'Toys & Games': 674790 }]} ^ SyntaxError: 无效语法
  • @Jake123 您的字典本身包含无效的 Python 语法。在您上面发布的示例中,最后一个括号 (]) 不是必需的。
【解决方案2】:

如果保证文件不受污染,你可以eval每一行:

with open('File.json', "r") as f:
    asins = [eval(line)['asin'] for line in f]

这是相同的代码,使用 @Ajax1234 的 ast.literal_eval() 来避免污染文件的问题,但使用我的列表理解,它单独评估每一行,因此不会将整个数据集存储为临时数据。

import ast

with open('File.json', "r") as f:
    asins = [ast.literal_eval(line)['asin'] for line in f]

对于基于评论的奖励问题,获取所有“also_bought”项目的列表,包括重复项:

import ast

also_bought = []
asins = []
with open('File.json', "r") as f:
    for line in f:
        item = ast.literal_eval(line)
        asins.append(item['asin'])
        if 'related' in item:
           related = item['related']
           if 'also_bought' in related:
              also_bought.extend(related['also_bought'])

【讨论】:

  • 谢谢!这行得通!但是你能解释一下它是如何为我工作的吗?
  • 每一行看起来都像是一个有效的 python 表达式。 eval 函数将字符串解释为好像它是 python 代码,因此字符串 { 'asin': '01234' } 将返回一个 python dict 对象。然后['asin'] 从字典中提取“asin”条目。 [ ... for line in f] 是标准的 python 列表理解...它遍历文件 f 中的所有行,调用每一行 line,生成列表。
  • 哦,虽然它有效,但不要使用它。使用ast.literal_eval 版本,@Ajax1234 ... 否则当有人污染文件并将实际代码放入其中时,您将执行他们的(可能是恶意的)代码。
  • @AJNeufield 尽管我收到无效的语法错误,但该方法对我不起作用
  • @AJNeufield 好的,谢谢你,最后一个问题,如果你再次查看我的数据文件,我如何才能一次获得一个数组中的所有 'also_bought' 值?希望这是有道理的。
猜你喜欢
  • 2014-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多