python - 从 csv 返回 python 中的多个值

标签 python regex csv return

我正在使用 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/

相关文章:

python - 使用 Python 为嵌套循环解析文件

python 正则表达式不使用 re.match 和 re.MULTILINE 标志匹配文件内容

javascript - 我可以在 Rails 表单上下载带有 `remote: true` 的 CSV 文件吗?

variables - 直接从csv读取var

python - 逻辑向量作为 Python 中的索引?

python - 有人解析过维基词典吗?

ios - 确认密码的正则表达式

javascript - 如何制作一个只允许数字和一个特殊字符的正则表达式?

powershell - 如何导入CSV文件中每行的前两个值电源外壳

python - 在 jupyter notebook : UnicodeDecodeError: codec can't decode byte xx 中读取一个文本文件