简体   繁体   English

如何清理和拆分以下字符串?

[英]How do I clean and split up the following string?

I have a column in my database which stores string in the following format:我的数据库中有一个列,它以以下格式存储字符串:

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

How do I extract the movie genres so I can use them seperately, after extraction I should have the following:如何提取电影类型以便我可以单独使用它们,提取后我应该有以下内容:

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

You can try this.你可以试试这个。 You can split them at every , and strip [] ' off of the word and use tuple unpacking.您可以将它们分开,并从单词中去除[] '并使用元组解包。

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

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

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

If you like regex:如果你喜欢正则表达式:

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

Try this :尝试这个 :

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

# Converting string to list 
res = inputString.strip('][').split(', ') 

g1= res[0]
g2= res[1]
g3= res[2]

There are quite a few ways to do this.有很多方法可以做到这一点。

  1. Using string manipulation as done above.如上所述使用字符串操作。

  2. Using ast.literal_eval() .使用ast.literal_eval()

  3. Using json.loads() .使用json.loads()

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

With a bit of mangling you can use json :通过一些修改,您可以使用json

import json

src = "['Action', 'Adventure', 'Comedy']"
src = src.replace("'",'"')

g = json.loads(src)
g1,g2,g3 = g

print(g1,g2,g3)

Output:输出:

Action Adventure Comedy

Try this code using regex:使用正则表达式试试这个代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM