【问题标题】:How do I read list of tuples as list type and tuples as tuple type in Python that are encoded in the form of string?如何在 Python 中将元组列表读取为列表类型并将元组读取为以字符串形式编码的元组类型?
【发布时间】:2019-08-21 00:51:06
【问题描述】:

从文件中读取元组列表时。这些值被读取为字符串,最初是元组格式的列表。如何从字符串中取回列表。我发布了我的问题的最小版本。

这是我尝试过的:

stli = '[(\'Rated 4.0\', \'RATED\\n  A beautiful place to dine in.The interiors take you back to the Mughal era. The lightings are just perfect.We went there on the occasion of Christmas and so they had only limited items available. But the taste and service was not compromised at all.The only complaint is that the breads could have been better.Would surely like to come here again.\'), (\'Rated 4.0\', \'RATED\\n  I was here for dinner with my family on a weekday. The restaurant was completely empty. Ambience is good with some good old hindi music. Seating arrangement are good too. We ordered masala papad, panner and baby corn starters, lemon and corrionder soup, butter roti, olive and chilli paratha. Food was fresh and good, service is good too. Good for family hangout.\\nCheers\'), (\'Rated 2.0\', \'RATED\\n  Its a restaurant near to Banashankari BDA. Me along with few of my office friends visited to have buffet but unfortunately they only provide veg buffet. On inquiring they said this place is mostly visited by vegetarians. Anyways we ordered ala carte items which took ages to come. Food was ok ok. Definitely not visiting anymore.\'), (\'Rated 4.0\', \'RATED\\n  We went here on a weekend and one of us had the buffet while two of us took Ala Carte. Firstly the ambience and service of this place is great! The buffet had a lot of items and the good was good. We had a Pumpkin Halwa intm the dessert which was amazing. Must try! The kulchas are great here. Cheers!\'), (\'Rated 5.0\', \'RATED\\n  The best thing about the place is itÃ\x83Â\x82Ã\x82Â\x92s ambiance. Second best thing was yummy ? food. We try buffet and buffet food was not disappointed us.\\nTest ?. ?? ?? ?? ?? ??\\nQuality ?. ??????????.\\nService: Staff was very professional and friendly.\\n\\nOverall experience was excellent.\\n\\nsubirmajumder85.wixsite.com\'), (\'Rated 5.0\', \'RATED\\n  Great food and pleasant ambience. Expensive but Coll place to chill and relax......\\n\\nService is really very very good and friendly staff...\\n\\nFood : 5/5\\nService : 5/5\\nAmbience :5/5\\nOverall :5/5\'), (\'Rated 4.0\', \'RATED\\n  Good ambience with tasty food.\\nCheese chilli paratha with Bhutta palak methi curry is a good combo.\\nLemon Chicken in the starters is a must try item.\\nEgg fried rice was also quite tasty.\\nIn the mocktails, recommend "Alice in Junoon". Do not miss it.\'), (\'Rated 4.0\', \'RATED\\n  You canÃ\x83Â\x82Ã\x82Â\x92t go wrong with Jalsa. Never been a fan of their buffet and thus always order alacarteÃ\x83Â\x82Ã\x82Â\x92. Service at times can be on the slower side but food is worth the wait.\'), (\'Rated 5.0\', \'RATED\\n  Overdelighted by the service and food provided at this place. A royal and ethnic atmosphere builds a strong essence of being in India and also the quality and taste of food is truly authentic. I would totally recommend to visit this place once.\'), (\'Rated 4.0\', \'RATED\\n  The place is nice and comfortable. Food wise all jalea outlets maintain a good standard. The soya chaap was a standout dish. Clearly one of trademark dish as per me and a must try.\\n\\nThe only concern is the parking. It very congested and limited to just 5cars. The basement parking is very steep and makes it cumbersome\'), (\'Rated 4.0\', \'RATED\\n  The place is nice and comfortable. Food wise all jalea outlets maintain a good standard. The soya chaap was a standout dish. Clearly one of trademark dish as per me and a must try.\\n\\nThe only concern is the parking. It very congested and limited to just 5cars. The basement parking is very steep and makes it cumbersome\'), (\'Rated 4.0\', \'RATED\\n  The place is nice and comfortable. Food wise all jalea outlets maintain a good standard. The soya chaap was a standout dish. Clearly one of trademark dish as per me and a must try.\\n\\nThe only concern is the parking. It very congested and limited to just 5cars. The basement parking is very steep and makes it cumbersome\')]'
json.loads(stli)

但我收到一个错误:

JSONDecodeError                           Traceback (most recent call last)
<ipython-input-93-78e7d355413d> in <module>()
----> 1 json.loads(stli)

c:\users\himanshu poddar\appdata\local\programs\python\python36-32\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    352             parse_int is None and parse_float is None and
    353             parse_constant is None and object_pairs_hook is None and not kw):
--> 354         return _default_decoder.decode(s)
    355     if cls is None:
    356         cls = JSONDecoder

c:\users\himanshu poddar\appdata\local\programs\python\python36-32\lib\json\decoder.py in decode(self, s, _w)
    337 
    338         """
--> 339         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    340         end = _w(s, end).end()
    341         if end != len(s):

c:\users\himanshu poddar\appdata\local\programs\python\python36-32\lib\json\decoder.py in raw_decode(self, s, idx)
    355             obj, end = self.scan_once(s, idx)
    356         except StopIteration as err:
--> 357             raise JSONDecodeError("Expecting value", s, err.value) from None
    358         return obj, end

JSONDecodeError: Expecting value: line 1 column 2 (char 1)

我已经尝试了所有可能的建议,但没有一个对我有用。我正在寻找使用 JSON 模块来解决它。

【问题讨论】:

  • 这不是有效的 JSON - JSON 没有元组。为什么要尝试使用json 库对其进行解码?
  • 如果json可以读取字符串格式的列表,那么为什么它不能读取包含在其中的元组的列表也作为列表。
  • JSON 中不存在“元组”的概念。就它映射到 python 而言,JSON 只理解 dicts ({"key": "value"}) 和列表 ([1, 2, 3])。请记住,JSON 与 python 无关——它起源于识别 Javascript 中的对象。您可能尝试的方法是将字符串stli 中的括号替换为方括号,然后然后在其上调用json.loads(),但这会更“正确”只需自己为此编写一个解释器。另见the official JSON specification
  • 另外,JSON 只使用了双引号。
  • @GreenCloakGuy 好吧不知道,我应该删除我的问题,因为问题本身的基础是错误的

标签: python json string decode encode


【解决方案1】:

您所拥有的不是有效的 JSON 字符串。你可能想试试ast.literal_eval:

import ast
# Replace with your string
stli = "['foo', ('bar', 'baz')]"
ast.literal_eval(stli) # ['foo', ('bar', 'baz')]

这基本上是eval 的安全版本,不会运行任意代码。顾名思义,它只接受文字。

顺便说一句,我用你的输入字符串测试了它,它给出了正确的输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 2018-07-20
    • 2018-08-24
    • 2022-11-21
    • 2011-06-17
    相关资源
    最近更新 更多