【问题标题】:Check if first letters of consecutive words in string match acronym of another string检查字符串中连续单词的首字母是否匹配另一个字符串的首字母缩写词
【发布时间】:2019-08-14 15:41:25
【问题描述】:

假设我有一个列表和一个字符串:

l=['hello my name is michael',
'hello michael is my name',
'hello michaela is my name',
'hello my name is michelle',
'hello i'm Michael',
'hello my lastname is michael',
'hello michael',
'hello my name is michael brown']

s="hello my name is michael"

在内部,我想搜索字符串中的每个单词并计算该字符串中的每个单词在每个列表元素中出现的次数。

hello my name is michael: 5
hello michael is my name: 5 (all words are present)
hello michaela is my name: 5 (extra characters at end of word are Ok)
hello my name is michelle: 4 
hello i'm Michael: 2 
hello my lastname is michael: 4 (extra characters are end of word are not Ok) 
hello michael: 2
hello my name is michael brown: 5

最后,我希望首先按最高计数项的顺序返回所有匹配项。所以输出将是:

hello my name is michael: 5
hello michael is my name: 5
hello michaela is my name: 5
hello my name is michael brown: 5
hello my name is michelle: 4 
hello my lastname is michael: 4
hello i'm Michael: 2 
hello michael: 2

这本质上是一个正则表达式匹配和排序问题,但我在这个问题上不知所措。任何建议如何继续执行任何或所有步骤?

【问题讨论】:

  • 您需要提供一个最小的工作示例stackoverflow.com/help/mcve,以便我们为您提供帮助。
  • 所以,我会给你一些建议。 1.你不需要正则表达式。 ; 2. 从您的字符串中使用 split() ; 3. 创建一个初始化计数器变量的函数; 4. 对于split() 中的每个术语,例如for i in range(len(s.split()):,使用ii 在字符串数组中翻找,因此您嵌入for ii in range(len(l)) 并搜索if s.split()[i] in l[ii]: counter += 1 Yaddda,Yadda

标签: python regex match


【解决方案1】:

我不明白您的预期输出。你的意思是这样的:

import re

l = ['hello my name is michael',
    'hello michael is my names',
    'hello michaela is my name',
    'hello my name is michelle',
    'hello i am Michael',
    'hello my lastname is michael',
    'hello michael',
    'hello my name is michael brown']

s = "Hello my name is Michael"

s = s.lower().split()
for item in l:
    d = item.lower().split()
    count = 0
    for ss in s:
        try:
            if ss in d or re.search(ss+"\w+",item.lower()).group() in d:
                count += 1
        except:
            pass
    print (item, count)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 2013-12-17
    • 2016-02-15
    • 1970-01-01
    • 2014-06-19
    • 2011-09-15
    相关资源
    最近更新 更多