python - 我们如何替换列表中字符串中的引号?
问题描述
我有一个字符串导致了一些问题。这是我的字符串。
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
推荐阅读
- r - 如何将计数总结为百分比而不是绝对值?
- javascript - 连续的水平 HTML 页面?
- powershell - ffmpeg - 转换文件但保持与原始相同的日期修改?
- rxjs - 如何监视像“take”这样的 Rxjs 操作符
- r - dplyr::filter 使用滞后/超前匹配多列的字符的行
- nullpointerexception - 我被迫为我的节点做一个空指针异常
- java - 扫描仪在辅助方法中给我错误
- powerbi - Microsoft Power BI 和 DAX - 计算非 YTD 度量的上一年周数的百分比变化
- javascript - 如何区分变量中现有的换行符和 \n?
- python - 如何在不重新启动内核的情况下创建距离矩阵