Python正则表达式编译分割字符串,使单词出现在前面

2024-04-25 12:21:38 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我得到了一根这样的绳子

text = "1234 I just ? shut * the door"

我想用正则表达式和重新编译()这样当我拆分列表时,所有的单词都在前面。你知道吗

也就是说,它应该是这样的。你知道吗

text = ["I", "just", "shut", "the", "door", "1234", "?", "*"]

我怎么用重新编译()以这种方式拆分字符串?你知道吗

import re
r = re.compile('regex to split string so that words are first').split(text)

如果你需要更多的信息,请告诉我。你知道吗

谢谢你的帮助。你知道吗


Tags: the字符串textimportre列表方式单词
3条回答

可以将sortedre.findall一起使用:

import re
text = "1234 I just ? shut * the door"
r = sorted(text.split(), key=lambda x:(x.isalpha(), x.isdigit(), bool(re.findall('^\W+$', x))), reverse=True)

输出:

['I', 'just', 'shut', 'the', 'door', '1234', '?', '*']

你不能用一个正则表达式就这么做。你可以写一个正则表达式来获取所有单词,然后再写另一个正则表达式来获取所有其他单词。你知道吗

import re

text = "1234 I just ? shut * the door"
r = re.compile(r'[a-zA-Z]+')
words = r.findall(text)
r = re.compile(r'[^a-zA-Z\s]+')
other = r.findall(text)

print(words + other) # ['I', 'just', 'shut', 'the', 'door', '1234', '?', '*']

IIUC,你不需要re。只需将str.splitsorted一起使用:

sorted(text.split(), key=lambda x: not x.isalpha())

输出:

['I', 'just', 'shut', 'the', 'door', '1234', '?', '*']

相关问题 更多 >