【问题标题】:How to split an element in a list into two elements?如何将列表中的元素拆分为两个元素?
【发布时间】:2019-05-20 05:27:03
【问题描述】:

我想拆分列表的元素,每个元素当前由电影和日期组成,但是我现在需要将它们分开,以便将它们添加到数据库中

这是我尝试过的

movies=["The Big Bad Fox and Other Tales (English subtitles)('23rd', 'May')"]
splitter=re.compile('(/(.+)').split
[part for img in movies for part in splitter(img) if part]

我该如何解决这个问题?

【问题讨论】:

标签: python regex list


【解决方案1】:

你快到了;D

import re

movies=["The Big Bad Fox and Other Tales (English subtitles)('23rd', 'May')"]

matcher = re.compile(r"^(.*)\((.*?)\)$").match

print([matcher(movie).groups() for movie in movies])

我建议使用RegExr 来学习和测试正则表达式。

【讨论】:

  • 谢谢,虽然我不希望 May 和 23rd 出现在不同的元素中,但这仍然很有帮助
  • 完成!只是一点点变化
【解决方案2】:

我不确定您希望将元素采用哪种格式,但您可以考虑相似之处,例如每个日期是否以“('”开头。

movies = ["The Big Bad Fox and Other Tales (English subtitles) ('23rd','May')"]
titles,dates = [],[]

for i in range(len(movies)):
    newTitle,newDate,sign,count = "","",False,0

    for char in movies[i]:
        if char == "(":
            sign = True
        elif sign == True:
            if char == "'":
                newDate += "(" + movies[i][count:]
                break
        else:
            newTitle += char
        count += 1
    titles.append(newTitle)
    dates.append(newDate)

print(titles)
print(dates)

输出:

['The Big Bad Fox and Other Tales ']

["('23rd','May')"]

希望这有帮助!

【讨论】:

  • 嘿,非常感谢,非常感谢它
【解决方案3】:

我们可以使用三个重要的python函数来解决这个问题: replace(pattern, replacement) string[start_position:end_position]string.index(pattern)

movies=["The Big Bad Fox and Other Tales (English subtitles)('23rd', 'May')"]

首先,制作2个模式,分别表示日期区域的开始和结束:

date_start = "('"
date_end = "')"

然后,删除该部分字符串以进行进一步分析:

date_information = movies[0][movies[0].index(date_start):movies[0].index(date_end)]

此时,“日期信息”应该是('23rd', 'May

然后,只需修剪前 2 个字符并替换单引号:

date_information = date_information[2:].replace("'", "")

这会给你一个最终的字符串,“date_information”,它应该是日期和月份,用逗号分隔:

23rd, May

最后,您可以将这个字符串用逗号 (date_information.split(",")) 拆分,以将其放入数据库中。

【讨论】:

  • 如何只保留名称?
  • name_information = movies[0][0:movies[0].index(date_start)] 应该为您提供电影名称(介于 0 和“23rd”之前的左括号之间。)感谢您的后续问题。我知道它不是基于正则表达式的,但它是一种方法!
【解决方案4】:

你可以使用split而不是使用正则表达式

movies=["The Big Bad Fox and Other Tales (English subtitles)('23rd', 'May')"]
splitter= movies[0].split(')(')
movie_name = f"{splitter[0]})"
date = f"({splitter[1]}"

这是解析,所以请记住,这只能在这种标准格式下工作。

【讨论】:

  • 尝试这个时我得到一个索引错误,说 date= f"({splitter[1]}" IndexError: list index out of range
  • 这个样本被 )( 分割,如果它们之间有空格,可能会导致。这个错误意味着它的 not 字符串没有被分割。
猜你喜欢
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-30
  • 2020-12-29
  • 2021-04-21
  • 2020-06-08
  • 2021-11-22
相关资源
最近更新 更多