gpt4 book ai didi

python - 如何在 Python csv writer 中将单引号替换为双引号?

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:12 42 4
gpt4 key购买 nike

我一直在尝试使用 python 输出一个 csv 文件。没有引号和数字,它工作正常。示例:

代码:

for n in G:
centrality = nx.degree_centrality(G)
betweeness = nx.betweenness_centrality(G)
edges = nx.edges(G, n)
csv_out.writerow([n, str(edges).replace("'",""), round(centrality[n],2), round(betweeness[n],2)])

输出:

24,"[(24, 31), (24, 64)]",0.02,0.04
25,"[(25, 77)]",0.01,0.0
26,"[(26, 49)]",0.01,0.0
27,"[(27, 75), (27, 79)]",0.02,0.02
20,"[(20, 9), (20, 84), (20, 40)]",0.03,0.03
21,"[(21, 77), (21, 64)]",0.02,0.02

我还需要能够输入字符串数据。示例:

Automation Specialist I,"[(Automation Specialist I, Data Coordiator)]",0.01,0.0
Community Outreach Specialist,"[(Community Outreach Specialist, Librarian)]",0.01,0.0
Research Assistant III,"[(Research Assistant III, Senior Quality Engineer)]",0.01,0.0
Cost Accountant,"[(Cost Accountant, Structural Engineer)]",0.01,0.0
Data Coordiator,"[(Data Coordiator, Technical Writer), (Data Coordiator, Automation Specialist I)]",0.02,0.01

但是我需要一个引用值以便在前端处理它。像这样:

Automation Specialist I,"[("Automation Specialist I", "Data Coordiator")]",0.01,0.0
Community Outreach Specialist,"[("Community Outreach Specialist", "Librarian")]",0.01,0.0
Research Assistant III,"[("Research Assistant III", "Senior Quality Engineer")]",0.01,0.0
Cost Accountant,"[("Cost Accountant", "Structural Engineer")]",0.01,0.0
Data Coordiator,"[("Data Coordiator", "Technical Writer"), ("Data Coordiator", "Automation Specialist I")]",0.02,0.01

所以我使用了下面的代码:

csv_out.writerow([n, str(edges).replace("'",'"'), round(centrality[n],2), round(betweeness[n],2)])

然而,结果是这样的:

对于数字:

24,"[(""24"", ""31""), (""24"", ""64"")]",0.02,0.04
25,"[(""25"", ""77"")]",0.01,0.0
26,"[(""26"", ""49"")]",0.01,0.0

对于字符串:

Automation Specialist I,"[(""Automation Specialist I"", ""Data Coordiator"")]",0.01,0.0
Community Outreach Specialist,"[(""Community Outreach Specialist"", ""Librarian")]"",0.01,0.0

我还尝试用撇号替换引号(列表之外),但没有成功。我也尝试使用下面的代码,但它给出了与上面相同的结果。

str(edges).replace("'",'"').replace('""','"')

我应该怎么做才能得到我想要的结果?我计划之后过滤输入的类型,以便仅在是字符串时才应用该技术。因为如果是数字,理想的输出就是第一个例子。当我使用最后一个时,我的前端代码处理文本和数字。但是当我使用第一个示例时,它不适用于文本,仅适用于数字。

你能帮帮我吗?如何将撇号替换为引号?非常感谢。

最佳答案

尝试用反斜杠转义双引号。例如

str(edges).replace("'","\"")

关于python - 如何在 Python csv writer 中将单引号替换为双引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33600087/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com