2011-11-05 25 views
2

我的单,多词短语的列表字符串:的Python:检测共享的话

terms = ['Electronic rock', 'Alternative rock', 'Indie pop']

我想检测terms[0]terms[1]份额字rock。有没有Pythonic的方式来做到这一点,而不是使用大量的for-loops,临时列表和split(' ')

基本上,我试图检测短语的半平等。

回答

6

可以使用dictonary记住哪些词出现在哪些条款:

from collections import defaultdict 

terms = ['Electronic rock', 'Alternative rock', 'Indie pop'] 
d = defaultdict(list) 
for term in terms: 
    for word in term.split(): 
     d[word].append(term) 

for k,v in d.iteritems(): 
    if len(v) > 1: 
     print k,v 

输出:

 
rock ['Electronic rock', 'Alternative rock'] 

看到它联机工作:ideone

+0

哈哈我是一半打字几乎完全一样的东西...也许一个2.7 +/3 +家伙会告诉我们一个更简洁计数器例? – Triptych

+0

那该死的美丽 –

+0

不错的作品表现出对字典的有效使用。 –

1

这是一个非常低效的解决方案对于这些简单的列表元素,但对于较长的字符串,您可以使用itertools' combinations生成一组2列表列表,然后使用difflib比较字符串。如果你只是处理两三个单词,这个解决方案不适合你。

1

访问How to find list intersection? 我认为答案可以从这个角度思考。在你的问题中,我们不知道你想表达什么结果。我想你最好列出你想得到的结果。

这里我列出可以给你一些提示的结果。 (好吧,没有分裂,我不认为这是明确的理解)。

a=terms[0].split() 
b=terms[1].split() 
list(set(a) & set(b)) 
1

上@MarkByers的答案的一些变化:

>>> from collections import defaultdict 
>>> 
>>> terms = [ 
...  'Electronic rock', 'Alternative rock', 'Indie pop', 
...  'baa baa black sheep', 
...  'Blackpool rock', # definition of "equality"? 
...  'Rock of ages', 
...  ] 
>>> 
>>> def process1(): 
...  d = defaultdict(list) 
...  for term in terms: 
...   for word in term.split(): 
...    d[word].append(term) 
...  for k,v in d.iteritems(): 
...   if len(v) > 1: 
...    print k,v 
... 
>>> def process2(): 
...  d = defaultdict(set) 
...  for term in terms: 
...   for word in term.split(): 
...    d[word.lower()].add(term) 
...  for k,v in d.iteritems(): 
...   if len(v) > 1: 
...    print k, sorted(list(v)) 
... 
>>> process1() 
rock ['Electronic rock', 'Alternative rock', 'Blackpool rock'] 
baa ['baa baa black sheep', 'baa baa black sheep'] 
>>> process2() 
rock ['Alternative rock', 'Blackpool rock', 'Electronic rock', 'Rock of ages'] 
>>>