结合使用斜杠分隔的单词以在Python中形成字符串

时间:2019-01-21 14:32:49

标签: python list nlp

我想找到一种方法来组合从字符串列表中以斜杠分隔的单词。这是一个示例:

df <- geocable %>% 
  mutate(count(nrow(geocable))) %>%
  group_by(n_distinct(geocable$CREATION_DTNR))

输出:

string1 = 'awesome/stupid'
string2 = 'red/blue/yellow' 
string3 = 'car'


def some_func(string1, strin2):

.
.
.

我尝试用'/'分割并添加字符串的内容,但是循环最终变得太大。我正在寻找的解决方案是针对一般情况,其中我不知道用斜杠分隔的单词数量。 预先感谢。

4 个答案:

答案 0 :(得分:1)

使用itertools.product()

from itertools import product

strings = [string1, string2, string3]    # Put all your slash-separated strings here
for x in product(*(s.split('/') for s in strings)):
    print(' '.join(x))

答案 1 :(得分:1)

我自己使用itertools.product(* args)找到了解决方案

string1 = ['awesome/stupid','red/blue/yellow','car']
s = [x.split('/') for x in string]

输出:

[['awesome', 'stupid'], ['red', 'blue', 'yellow'], ['car']]

然后

import itertools

prod = list(itertools.product())
prod

输出:

[('awesome', 'red', 'car'),
('awesome', 'blue', 'car'),
('awesome', 'yellow', 'car'),
('stupid', 'red', 'car'),
('stupid', 'blue', 'car'),
('stupid', 'yellow', 'car')]

答案 2 :(得分:0)

以天真的方式使用循环:

string1 = 'awesome/stupid'
string2 = 'red/blue/yellow' 
string3 = 'car'

for x in string1.split('/'):
    for y in string2.split('/'):
        print(f'{x} {y} {string3}')

# awesome red car
# awesome blue car                                              
# awesome yellow car                                          
# stupid red car                                              
# stupid blue car                                             
# stupid yellow car

答案 3 :(得分:0)

尝试此代码

string1 = 'awesome/stupid'
string2 = 'red/blue/yellow' 
string3 = 'car'

def(str1,str2,str3):
    list1=str1.split("/")
    list2=str2.split("/")
    list3=str3.split("/")
    for i in list1:
       for j in list2:
           for k in list3:
               print(i,j,k)

输出

'awesome red car'
'awesome blue car'
'awesome yellow car'    
'stupid red car'
'stupid blue car'
'stupid yellow car'

希望它会有所帮助:)