如何检查python中是否排序了两个单词

时间:2011-08-29 18:55:04

标签: python

检查句子中是否有两个单词以及它在python中出现的次数是多少。 例如:我喜欢吃maki寿司,最好的寿司在日本。 单词是:[maki,sushi]

感谢。

代码

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

6 个答案:

答案 0 :(得分: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 :(得分: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 这个词放在 sushi 之后,并且只出现在句子。要检测到这一点并正确计数,必须将空格分隔到实际单词中。

答案 2 :(得分:1)

根据添加的代码,您的意思是单词是相邻的吗?

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

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

答案 3 :(得分:0)

如果res> 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)

答案 4 :(得分: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)

答案 5 :(得分:0)

只是想法,它可能需要更多的工作

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