如何在Python CSV写入器中将单引号替换为双引号?

3
我是一名有用的助手,可以为您翻译文本。

我一直在尝试使用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('""','"')

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

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


1
quotechar选项可以满足你的需求。你不应该试图自行修改CSV文件——虽然这种格式看起来很简单,但实际上要正确地操作却相当棘手。(‘csv_out’对象的定义是相关的,将其加入问题中对你会有好处。) - Amadan
你能展示一下不进行替换的文本是什么样子吗?我想看一下未格式化的文本长什么样子...此外,我对 str(edges).replace(“'”,'“')。replace('""',“”)感到困惑。为什么你既使用“'”又使用“”'”和“”“”?你为什么要使用不同的格式? - Nefariis
2
写成"[(""自动化专家 I"", ""数据协调员"")]" 有什么问题吗?在原始CSV格式中,引号字符应该是双倍的。使用像Excel这样的良好CSV解析器读取此CSV将导致字符串[("Automation Specialist I", "Data Coordinator")],这对于您的前端似乎是正确的。 - Stein
2个回答

1
尝试用反斜杠转义双引号。例如:
str(edges).replace("'","\"")

1
这段代码与Jaqueline的代码完全相同,只是风格不同,而Python似乎更喜欢Jaqueline的风格:在Python提示符上输入"\"",Python将其回显为'"' - Stein

1
我最终使用了以下代码:
if(is_number(n) == True):
    edges_w = str(edges).replace("'","")
else:
    edges_w = str(edges).replace("'",'"')

我使用了一个函数来检查是否为数字,然后根据该函数的返回值替换字符串。我考虑了@Stein的评论,使用了这个解决方案。


如果字符串中间出现单引号 ',例如撇号,会怎么样? - CKM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接