0

Really need some help on this please-

I have a list:

mylist = "Cell Contents (Column Percentage, Counts, Statistical Test Results), Statistics (Overlap)"

I would like to find the following words in mylist:

'Statistical Test Results'
'Counts'
'Column Percentage'

Once found, I would like append those words to a new list in the order they appeared in mylist. So the new list should read:

newlist = ['Column Percentage','Counts','Statistical Test Results']

I know how to find a single word and append it to a new list using a for loop and in but I not too sure how to find multiple words and append them in the order they were found in the original list.

Thanks!

4

1 回答 1

2

我匹配了第一对括号之间的内容:

re.finditer(r'\((.*?)\)', mylist).next().groups()[0].split(', ')
['Column Percentage', 'Counts', 'Statistical Test Results']

re.finditer正则表达式搜索

  • 第一个参数是模式:它告诉搜索括号之间的第一项
  • 注意?里面的使用,让它不贪心,避免匹配过大... 看懂了,去掉再测试
  • 我们想要捕获括号内的表达式,这就是为什么我们在模式中有......括号。\(请注意转义括号与\)字符串中匹配的括号之间的区别,以及捕获的括号(和未转义的括号之间的区别)

finditer返回一个迭代器,它只有在我们让它运行后才会生效next。现在我们要获取字符串的捕获部分:这是groups方法([0]获取第一个也是唯一一个,但您可以使用正则表达式捕获多个部分)。

然后我们只是用昏迷分割结果,我们就完成了!

于 2013-07-23T13:34:31.077 回答