【问题标题】:How to split a sentence in python and put in list?如何在python中拆分句子并放入列表?
【发布时间】:2019-11-04 18:44:44
【问题描述】:

我制作了一个叫做艺术家的字符串:

artist = "Kanye West and Taylor Swift"
artistName = []

我想从“and”中拆分变量并将它们附加到艺术家姓名中。

所以输出将是 = ['Kanye', 'West', 'Taylor', 'Swift']

【问题讨论】:

标签: python list split


【解决方案1】:
[x for x in artist.split() if x!= 'and']

【讨论】:

  • 这仍然没有给出 OP 想要的东西,因为他也希望每个单词都被拆分。另外,你的答案可以归结为:split("and")
  • 这正是 OP 所要求的,并且是迄今为止如果艺术家姓名包含“和”时唯一不会失败的答案...
  • 哦,是的,很抱歉
【解决方案2】:

拆分方法如下:

artist = "Kanye West and Taylor Swift sheriand"
artistName = artist.split()
finalList=[]
for name in artistName:
    if name == "and":
        continue
    else:
        finalList.append(name)
print(finalList)

【讨论】:

  • 这将在输出列表中包含“and”作为条目,这是不需要的。
  • 坏主意...如果艺术家的名字中包含“和”,比如 Randy,该怎么办?
  • @ThierryLathuille 是的,这是有道理的
  • @ThierryLathuille 最好使用正则表达式匹配,但对于这种简单的情况,上述解决方案就足够了。
  • 现在代码按预期工作,即使名称包含“and”作为子字符串。它不能删除包含“和”的名称
【解决方案3】:

用空字符串替换and然后拆分

string ="Kanye West and Taylor Swift".replace(' and ', ' ').replace(' and', '').split()
print(string)

这也适用于正则表达式

import re
string = re.sub('(^and) | \s*and\s*', ' ', string).split()
print(string)

【讨论】:

  • 坏主意...如果艺术家的名字中包含“和”,比如 Randy,该怎么办?
  • 在替换之前在字符串“and”周围添加了一个额外的空格,当“and”是艺术家姓名的一部分时,使用空格然后拆分以解决问题,这是解决问题的另一种方法,但是我个人推荐@Lior Cohen 建议的答案
【解决方案4】:

我建议阅读 documentation 以了解 python 的 split() 函数。要获得所需的输出,您需要使用 split 两次 - 一次使用 'and',再次使用 ''。

artist = "Kanye West and Taylor Swift"
output = artist.split("and")
# Output looks like: ["Kanye West", "Taylor Swift"]

然后,您可以遍历列表中的每个名称并用“”分隔它们。 (我将把具体的实现留给你。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    相关资源
    最近更新 更多