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

问题描述 投票:2回答:3

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

"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是“新”,“约克”,第二个例子是实体是“你好”,“世界”。

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

例:

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

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

python regex split tokenize
3个回答
4
投票

使用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-z\d]+"
>>> 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]的捷径

1
投票

试试这个:

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.']


1
投票
"this is hello word program".split(' ')

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

© www.soinside.com 2019 - 2024. All rights reserved.