【发布时间】: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