【问题标题】:How do I clean and split up the following string?如何清理和拆分以下字符串?
【发布时间】:2020-03-21 17:58:51
【问题描述】:

我的数据库中有一个列,它以以下格式存储字符串:

"['Action', 'Adventure', 'Comedy']"

如何提取电影类型以便单独使用它们,提取后我应该有以下内容:

g1 = 'Action'  
g2 = 'Adventure'  
g3 = 'Comedy'

【问题讨论】:

  • 到底是什么问题?你有没有尝试过,做过任何研究? Stack Overflow 不是免费的代码编写服务,也不是提供个性化的指南和教程。请参阅:How to Askhelp centermeta.stackoverflow.com/questions/261592/…
  • 我如何提取电影类型以便我可以单独使用它们 为什么不修复以这种奇怪(充其量)格式存储数据的问题?

标签: python string list split


【解决方案1】:

你可以试试这个。您可以在每个 , 处拆分它们并从单词中删除 [] ' 并使用元组解包。

a="['Action', 'Adventure', 'Comedy']"

g1,g2,g3=[i.strip(" []'") for i in a.split(',')]

print(g1,g2,g3)
# Action Adventure Comedy

【讨论】:

    【解决方案2】:

    试试这个:

    inputString = "['Action', 'Adventure', 'Comedy']"
    
    # Converting string to list 
    res = inputString.strip('][').split(', ') 
    
    g1= res[0]
    g2= res[1]
    g3= res[2]
    

    有很多方法可以做到这一点。

    1. 使用如上所述的字符串操作。

    2. 使用ast.literal_eval()

    3. 使用json.loads()

    您可以在此处查看所有示例:https://www.geeksforgeeks.org/python-convert-a-string-representation-of-list-into-list/

    【讨论】:

      【解决方案3】:

      如果你喜欢正则表达式:

      import re
      g = "['Action', 'Adventure', 'Comedy']"
      g1,g2,g3 = re.findall(r"'(\w+)'",g)
      print(g1,g2,g3)
      

      【讨论】:

        【解决方案4】:

        稍加修改后,您可以使用json

        import json
        
        src = "['Action', 'Adventure', 'Comedy']"
        src = src.replace("'",'"')
        
        g = json.loads(src)
        g1,g2,g3 = g
        
        print(g1,g2,g3)
        

        输出:

        Action Adventure Comedy
        

        【讨论】:

          【解决方案5】:

          使用正则表达式试试这个代码:

          import re
          g = "['Action', 'Adventure', 'Comedy']"
          [g1, g2, g3] = " ".join(re.findall("[a-zA-Z]+", g)).split(" ")
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-01-15
            • 2013-10-12
            • 2020-06-20
            • 1970-01-01
            • 2011-12-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多