简体   繁体   中英

How to check if two words are ordered in python

what 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
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'

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

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 over the spaces into the actual words. 句子在空格处分成实际的单词。

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)) 

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM