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

2024-10-02 06:34:35 发布

您现在位置:Python中文网/ 问答频道 /正文

检查两个单词在句子中是否有顺序以及在python中出现多少次的bes方法是什么。 我喜欢吃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

Tags: inrel1forif顺序单词句子
3条回答
s = 'I like to eat maki sushi and the best sushi is in Japan'

检查顺序

^{pr2}$

如何计数

s.split().count('maki')

注(基于以下讨论):

假设句子是'我喜欢makim胜过寿司或maki'。意识到makim是另一个单词maki,单词maki放在sushi之后,在句子中只出现一次。要检测到这一点并正确计数,句子必须在空格处拆分成实际单词。在

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.

不完全是最有效的方法,但更容易理解。在

根据添加的代码,你是说单词是相邻的?在

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

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

相关问题 更多 >

    热门问题