[英]How do I split a sentence into several phrases?
我想把一个句子分成几个有意义的部分,例如:我有一个来自用户的输入: Samsung phone case
,我想分成一个列表:['三星手机','手机壳','三星手机壳' ],这意味着'三星手机'是一个有效对象,'手机壳'是另一个有效对象,'三星手机壳'也是一个有效对象,如何用python做到这一点?
It doesn't look like you want a split, but rather combinations (or some kind of power set).看起来您并不想要拆分,而是想要组合(或某种电源组)。 Splitting is a necessary intermediate though:不过,拆分是必要的中间环节:
s = 'Samsung phone case'
from itertools import combinations, chain
l = s.split()
list(chain(*(map(' '.join, combinations(l, r=n)) for n in range(2,len(l)+1))))
output:输出:
['Samsung phone', 'Samsung case', 'phone case', 'Samsung phone case']
You can use indexing if you know the input string.如果您知道输入字符串,则可以使用索引。 For example:例如:
txt = "Samsung phone case"
x = txt[0:13]
y = txt[8:19]
new_txt = [x, y, txt]
print(new_txt)
The output will be:输出将是:
>>> ['Samsung phone', 'phone case', 'Samsung phone case']
Alternatively, you can use Regular Expressions, such as:或者,您可以使用正则表达式,例如:
import re
txt = ['Samsung phone case']
x = re.search('(.*?) (case)', txt).group(1)
and so on.等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.