[英]Python Regex Compile Split string so that words appear first
说我得到了一个像这样的字符串
text = "1234 I just ? shut * the door"
我想使用带有re.compile()的正则表达式,这样当我拆分列表时,所有单词都在前面。
即它看起来应该是这样的。
text = ["I", "just", "shut", "the", "door", "1234", "?", "*"]
如何使用re.compile()以这种方式拆分字符串?
import re
r = re.compile('regex to split string so that words are first').split(text)
如果您需要更多信息,请与我们联系。
感谢您的帮助。
IIUC,你不需要re
。 只需使用str.split
与sorted
:
sorted(text.split(), key=lambda x: not x.isalpha())
输出:
['I', 'just', 'shut', 'the', 'door', '1234', '?', '*']
您可以使用re.findall
sorted
:
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', '?', '*']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.