拆分字符串的最佳方法是什么?
text = "hello there how are you"用Python?
所以我最终会得到这样的数组:
['hello there', 'there how', 'how are', 'are you']我试过这样做:
liste = re.findall('((\S+\W*){'+str(2)+'})', text)
for a in liste:
print(a[0])但我得到了:
hello there
how are
you如何使findall函数在搜索时只移动一个令牌?
发布于 2019-07-11 22:57:22
下面是使用re.findall的解决方案
>>> import re
>>> text = "hello there how are you"
>>> re.findall(r"(?=(?:(?:^|\W)(\S+\W\S+)(?:$|\W)))", text)
['hello there', 'there how', 'how are', 'are you']查看re:https://docs.python.org/3/library/re.html的Python
(?=...)前瞻性断言(?:...)非捕获规则括号发布于 2019-07-11 22:46:03
如果regex不是必需的,您可以这样做:
l = text.split(' ')
out = []
for i in range(len(l)):
try:
o.append(l[i] + ' ' + l[i+1])
except IndexError:
continue解释:
首先拆分空格字符上的字符串。结果将是一个列表,其中每个元素都是句子中的一个单词。实例化一个空列表以保存结果。循环遍历单词列表,将由空格分隔的两个单词组合添加到输出列表中。这将在访问列表中的最后一个单词时抛出一个IndexError,只需捕获它并继续,因为您似乎不希望结果中只有这个单词。
发布于 2019-07-11 22:47:37
我不认为你真的需要这个regex。
我知道您需要一个列表,其中每个元素包含两个单词,后者也是以下元素中的前一个。我们可以很容易地做到这样:
string = "Hello there how are you"
liste = string.split(" ").pop(-1)
# we remove the last index, as otherwise we'll crash, or have an element with only one word
for i in range(len(liste)-1):
liste[i] = liste[i] + " " + liste[i+1]https://stackoverflow.com/questions/56998097
复制相似问题