0

我有一个这样的字符串Delete File/Folder。我需要根据/等价于or.

最后需要从中生成两个字符串,Delete File一个字符串和另一个字符串Delete Folder

我尝试了非常天真的方法,我检查索引,/然后用一堆条件形成字符串。

当我们有类似的字符串时,它有时会失败File/Folder Deleted


编辑:

如果您拆分,/那么对于案例 1,我们有Delete FileFolder。然后我将检查第一个字符串中是否存在空格,而存在的空格是第二个字符串。

空格数较少的将替换为第一个字符串最后一个元素。这变得越来越复杂。

4

4 回答 4

2

在 的情况下Delete File/Folder,思考为什么这个词Delete会分配给两者,File并且Folder可能有助于我们在词法解析时直观地做出的固有假设。

例如,它将在 theilreturn之间解析["Delete File", "Delete FiFolder"]

听起来您想根据空格将字符串拆分为单词,然后根据空格拆分每个单词/以生成新的完整字符串。

>>> import itertools

>>> my_str = "Delete File/Folder"
>>> my_str = ' '.join(my_str.split()).replace('/ ', '/').replace(' /', '/')  # First clean string to ensure there aren't spaces around `/`
>>> word_groups = [word.split('/') for word in my_str.split(' ')]
>>> print [' '.join(words) for words in itertools.product(*word_groups)]
['Delete File', 'Delete Folder']
于 2015-10-30T11:02:23.807 回答
1
str = "Do you want to Delete File/Folder?"

word = str.split(" ")

count = str.count("/")

c = True

for j in range(0,2*count):
    for i in word:
        if("/" in i):
            words = i.split("/")

            if c:
                print words[1],

            else:
                print words[0],

        else:
            print i, # comma not to separate line 
    c = not c
    print

输出

Do you want to Delete File
Do you want to Delete Folder?
于 2015-10-30T11:20:53.707 回答
1

你想要那个吗?如果您想要更通用的解决方案,请发表评论。

lst = your_string.split()[1].split("/")

finalList=[]
for i in lst:
    finalList.append("Delete {0}",i)

print finalList

对于字符串:

Delete File/Folder

输出:

['Delete File', 'Delete Folder']
于 2015-10-30T10:52:02.340 回答
1
st1 = "Do you want to Delete File/Folder"
st2 = "File/Folder Updated" 

def spl(st):
    import re
    li = []
    ff = re.search(r'\w+/\w+',st).group()
    if ff:
        t = ff.split('/')
        l = re.split(ff,st)
        for el in t:
            if not l[0]:
                li.append((el + ''.join(l)))
            else:
                li.append((''.join(l) + el))
    return li

    for item in st1,st2:
        print(spl(item))

    ['Do you want to Delete File', 'Do you want to Delete Folder']
    ['File Updated', 'Folder Updated']
于 2015-10-30T10:56:03.807 回答