首页 > 解决方案 > 我们如何替换列表中字符串中的引号?

问题描述

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

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

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

标签: pythonpython-3.x

解决方案


也许这对你有帮助。请注意,我将 ' 放在 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

推荐阅读