2011-08-29 88 views
1

什么是bes way方法检查两个单词是否在句子中排序以及它在python中发生多少次。例如:我喜欢吃寿司寿司和最好的日本寿司。 单词为:[maki,寿司]如何检查两个单词是否在python中排序

谢谢。

代码

import re 

x="I like to eat maki sushi and the best sushi is in Japan" 
x1 = re.split('\W+',x) 
l1 = [i for i,m in enumerate(x1) if m == "maki"] 
l2 = [i for i,m in enumerate(x1) if m == "sushi"] 


ordered = [] 
for i in l1: 
    for j in l2: 
     if j == i+1: 
      ordered.append((i,j)) 

print ordered 
+5

任何代码尝试,你可以提供你自己吗? – steabert

+1

添加了,但效率不高 – gizmo

+0

所以你想要“每一对索引(x,y)使得x

回答

1

根据所添加的代码,你的意思是的话是相邻的?

为什么不把它们放在一起:

print len(re.findall(r'\bmaki sushi\b', sent)) 
+0

没有OP的意思,所以这个答案是无用的。 –

+0

@gizmo说“if j == i + 1” – eph

+0

@jakob - thx这实际上解决了我的问题:)(我也允许“ - ”在两个单词之间) – gizmo

0

如果解析度> 0: 词在句中

words = ["sushi", "maki", "xxx"] 
sorted_words = sorted(words) 
sen = " I like to eat maki sushi and the best sushi is in Japan xxx"; 
ind = map(lambda x : sen.index(x), sorted_words) 
res = reduce(lambda a, b: b-a, ind) 
1
def ordered(string, words): 
    pos = [string.index(word) for word in words] 
    return pos == sorted(pos) 

s = "I like to eat maki sushi and the best sushi is in Japan" 
w = ["maki", "sushi"] 
ordered(s, w) #Returns True. 

不完全是这样做的最有效的方式,但更简单的分类理解。

+1

为什么使用'assert'如果命令已经返回bool? – Remi

+0

只是为了证明它工作正常,因为给出的例子应该返回True。断言只是为了表明它不会失败 –

+0

好。顺便说一句,我喜欢你的功能。但请参阅我们对[我的答案]的讨论(http://stackoverflow.com/questions/7234518/how-to-check-if-two-words-are-ordered-in-python/7234654#7234654):我想你需要将句子拆分... – Remi

1
s = 'I like to eat maki sushi and the best sushi is in Japan' 

检查顺序

indices = [s.split().index(w) for w in ['maki', 'sushi']] 
sorted(indices) == indices 

怎么算

s.split().count('maki') 

注(基于下面讨论):

假设句子是'我喜欢makim比寿司或maki'。认识到 makim是另一个词比 maki,单词 maki被放在寿司后面,并且在句子中只出现一次。为了检测这个并且正确计数,句子必须在空间上拆分成实际词语

+0

这是复杂的? –

+0

编辑:刚才看到我把它排序()它不属于... – Remi

+0

你在做s.split()。index(w)。你不需要。 –

0

一个正则表达式的解决方案:)

import re 
sent = 'I like to eat maki sushi and the best sushi is in Japan' 
words = sorted(['maki', 'sushi']) 
assert re.search(r'\b%s\b' % r'\b.*\b'.join(words), sent) 
+0

Bah世界需要更少的编码 –

+0

%s考虑到较新的string.format()方法,格式化不太适合未来的验证方法 – Remi

0

就和想法,这可能需要一些更多的工作

(sentence.index('maki') <= sentence.index('sushi')) == ('maki' <= 'sushi') 
+0

多个单词怎么办? –

+0

'index()'会给你最低的索引。如果该单词不在字符串中,它也会引发'ValueError'。这只适用于最简单的情况。 –

相关问题