【问题标题】:How can we replace quotation marks in a string in a list?我们如何替换列表中字符串中的引号?
【发布时间】:2021-09-22 17:10:43
【问题描述】:

我有一个字符串导致了一些问题。这是我的字符串。

my_string = "'{'place_id': X, 'licence': 'X', 'osm_type': 'X', 'osm_id': X,'boundingbox': X, 'lat': 'X', 'lon': 'X', 'display_name': 'X', 'class': 'X', 'type': 'X','importance': X})'"

如果开头没有"',结尾没有'",则不会被视为字符串。

也许我以错误的方式创建字符串。没有把握。无论如何,这就是我最终的结果。

["'{'place_id': X, 'licence': 'X', 'osm_type': 'X'}'",
{'place_id': 177948251,
  'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',
  'osm_type': 'way'},
{'place_id': 306607940,
  'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',
  'osm_type': 'way'}]

我正在尝试将此列表转换为数据框,但出现此错误:

'AttributeError: 'str' object has no attribute 'keys''

我认为问题来自列表中的第一项:

"''"

所以,我尝试对列表中的项目执行 str.replace,就像这样。

new_strings = []
for j in final_list:
   new_string = str.replace("""'{""", "{") 
   new_string = str.replace("""}'""", "}")
   new_strings.append(new_string)
   
my_df = pd.DataFrame(new_string)

当我尝试运行它时,我得到了这个错误。

Traceback (most recent call last):

  File "<ipython-input-83-424d9a0504f8>", line 3, in <module>
    new_string = str.replace("""'{""","{")

TypeError: replace expected at least 2 arguments, got 1

知道如何解决这个问题吗?

【问题讨论】:

  • 你需要告诉它在循环中替换 j。
  • 无论生成什么字符串,都应该更改。
  • 那个字符串是一团糟。这就像一个 Python dict 文字包裹在一个字符串中,该字符串包裹在另一个字符串中。解开它会很脆弱,因为单引号不会嵌套。
  • 好像你只是想访问 python dict,它被引号包裹了两次。试试a = eval ('the-string-which-is-actually-a-dict')
  • 试试这个print(eval("'{'place_id': 'X', 'licence': 'X', 'osm_type': 'X'}'"[1:-1]))

标签: python python-3.x


【解决方案1】:

也许这对你有帮助。请注意,我将 ' 放在 X 周围,因为我认为这是原始版本中的错字。

import json

old_list = [
    "'{'place_id': 'X', 'licence': 'X', 'osm_type': 'X'}'",
    {
        'place_id': 177948251,
        'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',
        'osm_type': 'way'
    },
    {
        'place_id': 306607940,
        'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',
        'osm_type': 'way'
    }
]

new_list = []
for item in old_list:
    if isinstance(item, str):
        # if we strip the surrounding ' and replace all other ' with "
        # this looks like a json document
        item_json = item.strip("'").replace("'", '"')
        item_dict = json.loads(item_json)
        new_list.append(item_dict)
    elif isinstance(item, dict):
        # perfect, we can keep this item as it is
        new_list.append(item)
    else:
        # oh oh, we got an unexpected type
        raise TypeError

【讨论】:

  • 现在可以使用了!谢谢大家!!
猜你喜欢
  • 2019-11-01
  • 2022-11-22
  • 2015-11-29
  • 2019-11-02
  • 2018-11-28
  • 2015-05-24
  • 2017-03-25
  • 2021-11-15
  • 1970-01-01
相关资源
最近更新 更多