从csv返回python中的多个值
我正在使用一个CSV文件,从中可能会得到多个值。例如,包含书籍的文件,其中可能有多个作者,例如从csv返回python中的多个值,python,regex,csv,return,Python,Regex,Csv,Return,我正在使用一个CSV文件,从中可能会得到多个值。例如,包含书籍的文件,其中可能有多个作者,例如{Ben Norrington | Chad Andersson}。他们一起写了一本书 在我的代码中,我使用正则表达式按|进行拆分,并删除{和}。它很好用 当我想返回作者的名字时,问题就来了。我只知道第一个名字,没有第二个。我怎样才能两者兼得 这是我从CSV文件中获取一列的代码。代码是用python 2.7编写的 def ifseveral(x): if "{" not in x and
{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中断循环,因此只返回第一次分割。您必须调整逻辑,以便将拆分添加到datatstructure(甚至一个简单的字符串),并在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
函数只能返回单个对象。该对象可以是简单的对象,如整数或字符串,也可以是更复杂的对象,如对象列表,也可以是生成器
return
语句从函数返回。该函数不能(不能)继续执行
由于将return
语句放入for
循环中,因此当到达返回时,循环不再继续处理其他数据
一个解决方案是:建立一个列表并返回它
def ifseveral(x):
# ...
result = []
for string in splits:
# ...
if "(" in string:
splitpar = ""
splited = string.split("(")
splitpar += splited[0][0:]
result.append(splitpar)
else:
result.append(string)
return result
foo = ifseveral("something")
print(foo)
print(len(foo))
for name in foo:
print("One of the names is", name)
另一种解决方案是将函数作为生成器:
def ifseveral(x):
# ...
for string in splits:
# ...
if "(" in string:
splitpar = ""
splited = string.split("(")
splitpar += splited[0][0:]
yield splitpar
else:
yield string
return result
foo = ifseveral("something")
print(foo)
for name in foo:
print("One of the names is", name)
您可以简化
splitpar=“”;splited=string.split(“”;splitpar+=splited[0][0:
到只splitpar=string.split(“”[0]
)。