How to check if two words are ordered in python
wh开发者_运维百科at is the bes way tho check if two words are ordered in sentence and how many times it occurs in python. For example: I like to eat maki sushi and the best sushi is in Japan. words are: [maki, sushi]
Thanks.
The code
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
According to the added code, you mean that words are adjacent?
Why not just put them together:
print len(re.findall(r'\bmaki sushi\b', sent))
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.
Not exactly the most efficient way of doing it but simpler to understand.
s = 'I like to eat maki sushi and the best sushi is in Japan'
check order
indices = [s.split().index(w) for w in ['maki', 'sushi']]
sorted(indices) == indices
how to count
s.split().count('maki')
Note (based on discussion below):
suppose the sentence is 'I like makim more than sushi or maki'. Realizing that makim is another word than maki, the word maki is placed after sushi and occurs only once in the sentence. To detect this and count correctly, the sentence must be split over the spaces into the actual words.
if res > 0: words are sorted in the sentence
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)
A regex solution :)
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)
Just and idea, it might need some more work
(sentence.index('maki') <= sentence.index('sushi')) == ('maki' <= 'sushi')
精彩评论