Python用括号分隔字符串

2024-06-25 05:37:57 发布

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

不久前我问了一个问题(Python splitting unknown string by spaces and parentheses),这个问题很有效,直到我不得不改变我的思维方式。我还没有掌握regex,所以我需要一些帮助。

如果用户键入:

new test (test1 test2 test3) test "test5 test6"

我希望它看起来像变量的输出,如下所示:

["new", "test", "test1 test2 test3", "test", "test5 test6"]

换言之,如果一个单词被空格隔开,则将其与下一个单词分开;如果该单词在括号中,则将括号中的整组单词分开并删除它们。引号也一样。

我目前使用的代码不符合上述标准(从以上链接中的答案):

>>>import re
>>>strs = "Hello (Test1 test2) (Hello1 hello2) other_stuff"
>>>[", ".join(x.split()) for x in re.split(r'[()]',strs) if x.strip()]
>>>['Hello', 'Test1, test2', 'Hello1, hello2', 'other_stuff']

这很好,但有一个问题,如果你有:

strs = "Hello Test (Test1 test2) (Hello1 hello2) other_stuff"

它将Hello和Test合并为一个split而不是两个。

它也不允许同时使用括号和引号。


Tags: testhellonew单词括号splitothertest1
3条回答

这是你所期望的

import re, itertools
strs = raw_input("enter a string list ")

res1 = [ y for y in list(itertools.chain(*[re.split(r'\"(.*)\"', x) 
        for x in re.split(r'\((.*)\)', strs)])) 
        if y <> '']

set1 = re.search(r'\"(.*)\"', strs).groups()
set2 = re.search(r'\((.*)\)', strs).groups()

print [k for k in res1 if k in list(set1) or k in list(set2) ] 
   + list(itertools.chain(*[k.split() for k in res1 if k 
   not in set1 and k not in set2 ]))

答案很简单:

re.findall('\[[^\]]*\]|\([^\)]*\)|\"[^\"]*\"|\S+',strs)

你的问题没有很好地解决。

你对规则的描述是

In other words if it is one word seperated by a space then split it from the next word, if it is in parentheses then split the whole group of words in the parentheses and remove them. Same goes for the commas.

我猜你用逗号是指反逗号==引号。

然后用这个

strs = "Hello (Test1 test2) (Hello1 hello2) other_stuff"

你应该明白

["Hello (Test1 test2) (Hello1 hello2) other_stuff"]

因为所有的东西都被反逗号包围。最有可能的是,您不需要关心最大的倒逗号。

我提议这样,尽管一个丑陋的机器人

import re, itertools
strs = raw_input("enter a string list ")

print [ y for y in list(itertools.chain(*[re.split(r'\"(.*)\"', x) 
        for x in re.split(r'\((.*)\)', strs)])) 
        if y <> '']

获取

>>> 
enter a string list here there (x y ) thereagain "there there"
['here there ', 'x y ', ' thereagain ', 'there there']

相关问题 更多 >