如何在Python中检查两个词是否有序

1 投票
6 回答
793 浏览
提问于 2025-04-17 00:33

在Python中,怎么检查两个词在句子中是否有顺序,并且统计它们出现的次数呢?

举个例子:我喜欢吃卷寿司,而最好的寿司在日本。

这里的词是:[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 个回答

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
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'。意识到 makimmaki 是不同的词后,maki 在句子中出现在 sushi 之后,并且只出现了一次。为了正确识别和计数,句子 必须通过空格分开 成为实际的单词。

2

根据你添加的代码,你是说这些词是相邻的吗?

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

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

撰写回答