我正在使用 CSV 文件,我可能会从中获取多个值。例如,包含书籍的文件,可能有多个作者,例如 {Ben Norrington|Chad Andersson}
。他们一起写了一本书。
在我的代码中,我使用正则表达式按 |
进行拆分,并删除 {
和 }
。效果很好。
当我想返回作者姓名时,问题就出现了。我只得到第一个名字,而不是第二个名字。我如何同时获得两者?
这是我的代码,它从 CSV 文件中获取一列。代码是用python 2.7
def ifseveral(x):
if "{" not in x and "(" not in x and x != "NULL":
return x
elif "{" in x:
splits =""
splits = x.split("|")
for i in splits:
string = i
string = re.sub('[{}]', '', string)
if "(" in string:
splitpar = ""
splited = string.split("(")
splitpar += splited[0][0:]
return splitpar
else:
**return string** #here is the problem
else:
return "No information available"
最佳答案
Return 会中断循环,因此仅返回第一个分割。您必须调整逻辑,以便将拆分添加到数据结构(甚至简单的字符串)中,并在 for 循环后返回整个结构。 尽管未经测试,但这可以完成这项工作。
def ifseveral(x):
if "{" not in x and "(" not in x and x != "NULL":
return x
elif "{" in x:
splits =""
splits = x.split("|")
return_value = ""
for i in splits:
string = i
string = re.sub('[{}]', '', string)
if "(" in string:
splitpar = ""
splited = string.split("(")
splitpar += splited[0][0:]
return splitpar
else:
return_value += string+" "
return return_value
else:
return "No information available
关于python - 从 csv 返回 python 中的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34358425/