簡體   English   中英

如何檢查兩個單詞是否在python中排序

[英]How to check if two words are ordered in python

檢查兩個單詞是否在句子中排序以及在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
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.

並不是最有效的方法,而是更容易理解。

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

注意(基於下面的討論):

. 假設句子是 is another word than , the word is placed after and occurs only once in the sentence. 意識到是另一個詞比 ,字放置后,並在句子中只發生一次。 為了檢測到這一點並正確計數, 必須將句子在空格處分成實際的單詞。

根據添加的代碼,您是說單詞相鄰嗎?

為什么不將它們放在一起:

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

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

正則表達式解決方案:)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM