如何在 python 中将字符串拆分为列表并将两个已知令牌合并为一个



对于给定的字符串,例如:

"Today is a bright sunny day in New York"

我想让我的清单成为:

['Today','is','a','bright','sunny','day','in','New York']

再比如:

"This is a hello world program"

该列表是: ['This', 'is', 'a', 'hello world', 'program']

对于每个给定的字符串 S,我们有需要保持在一起的实体 E。第一个示例的实体 E 为"New"、"York",第二个示例的实体为 "hello","world"。

我试图通过正则表达式完成它,但我没有成功按空格拆分并合并两个实体。

例:

regex = "(navy blue)|[a-zA-Z0-9]*" match = re.findall(regex, "the sky looks navy blue.",re.IGNORECASE) print match

输出: ['', '', '', '', '', '', 'navy blue', '', '']

使用 re.findall 而不是 split 并在表示要提取的字符串的字符类之前交替提供实体

>>> s = "Today is a bright sunny day in New York"
>>> re.findall(r'New York|w+', s)
['Today', 'is', 'a', 'bright', 'sunny', 'day', 'in', 'New York']
>>> s = "This is a hello world program"
>>> re.findall(r'hello world|w+', s)
['This', 'is', 'a', 'hello world', 'program']

w更改为适当的字符类,例如:[a-zA-Z]


对于添加到问题的其他示例

>>> regex = r"navy blue|[a-zd]+"
>>> re.findall(regex, "the sky looks navy blue.", re.IGNORECASE)
['the', 'sky', 'looks', 'navy blue']
  • 使用r字符串构造正则表达式模式是一种很好的做法
  • 此处不需要分组
  • 使用 + 而不是 *以便必须至少匹配一个字符
  • 由于指定了re.IGNORECASE,因此在字符类中a-zA-Z就足够了。 也可以使用re.I作为快捷方式
  • d[0-9]的捷径

试试这个:

text = "Today is a bright sunny day in New York"
new_list = list(map(str, text.split(" ")))

这应该会为您提供以下输出['Today', 'is', 'a', 'bright', 'sunny', 'day', 'in', 'New', 'York']

下一个字符串相同:

hello = "This is a hello world program."
yet_another_list = list(map(str, hello.split(" ")))

给你['This', 'is', 'a', 'hello', 'world', 'program.']

"this is hello word program".split(' ')

拆分将自动生成一个列表。 您可以使用任何字符串或单词或字符进行拆分。

最新更新