如何替换列表中字符串中的引号?



我有一个字符串引起一点问题。这是我的字符串。

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

你知道怎么解决这个问题吗?

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

最新更新