我可以在python上拆分一些文本吗?

2024-07-05 09:03:36 发布

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

我想在python上拆分文本并参与其中,例如:

let the blue sky meet the blue sea

我想要这个结果:

blue sky

这是我的密码

text = "let the blue sky meet the blue sea"
bluee = text.split("the", 1)[1]
print bluee

代码的结果是 blue sky meet the blue sea


Tags: the代码text文本密码bluesplitprint
3条回答

这将去掉正文的行乞部分,然后是正文的最后一部分。 raw_input()input()可用于让用户确定要剥离的代码部分

text = "let the blue sky meet the blue sea"
bluee = text.split("the", 1)[1]
skyy = bluee.split("meet", 1)[0]
print skyy
 text = "let the blue sky meet the blue sea"
 text=text.split(" ")
 text=text[2]+" "+text[3]
 print(text)

首先,我认为理解分裂语法会对我们有所帮助。你知道吗

你知道吗文本.拆分(sep,max):(sep和max都是可选的)

sep:分隔文本的方式(默认为空格)

max:要拆分的最大组数(默认值为-1,表示所有组)


你的情况是这样的:

 text = "let the blue sky meet the blue sea"
## short answer
print(' '.join(text.split()[2:4]))

解释

我们将做三个步骤

# split it by default
list_word = text.split() # return ['let', 'the', 'blue', 'sky', 'meet', 'the', 'blue', 'sea']
# then we choose from 3rd to 4th elements
target_word = list_word[2:4] # return ['blue', 'sky']
# connect all element together with space
result = ' '.join(target_word)
print(result)

相关问题 更多 >