问题描述
我正在尝试开发一个 python 算法来检查一个字符串是否可以是另一个单词的缩写.例如
I'm trying to develop a python algorithm to check if a string could be an abbrevation for another word. For example
fck
是fc kopenhavn
的匹配项,因为它匹配单词的第一个字符.fhk
不匹配.fco
不应与fc kopenhavn
匹配,因为没有人会将 FC Kopenhavn 缩写为 FCO.irl
与现实生活中的匹配.
ifk
是ifk goteborg
的匹配项.aik
是allmanna idrottskluben
的匹配项.aid
与allmanna idrottsklubben
匹配.这不是真正的团队名称缩写,但我想很难排除它,除非您应用特定领域的知识,了解瑞典语缩写的形成方式.manu
是manchester United
的匹配项.
fck
is a match forfc kopenhavn
because it matches the first characters of the word.fhk
would not match.fco
should not matchfc kopenhavn
because no one irl would abbrevate FC Kopenhavn as FCO.irl
is a match forin real life
.ifk
is a match forifk goteborg
.aik
is a match forallmanna idrottskluben
.aid
is a match forallmanna idrottsklubben
. This is not a real team name abbrevation, but I guess it is hard to exclude it unless you apply domain specific knowledge on how Swedish abbrevations are formed.manu
is a match formanchester united
.
很难描述算法的确切规则,但我希望我的例子能说明我所追求的.
It is hard to describe the exact rules of the algorithm, but I hope my examples show what I'm after.
更新 我在显示匹配字母大写的字符串时犯了一个错误.在实际场景中,所有字母都是小写的,因此并不像检查哪些字母是大写那么容易.
Update I made a mistake in showing the strings with the matching letters uppercased. In the real scenario, all letters are lowercase so it is not as easy as just checking which letters are uppercased.
推荐答案
这通过了所有测试,包括我创建的一些额外测试.它使用递归.以下是我使用的规则:
This passes all the tests, including a few extra I created. It uses recursion. Here are the rules that I used:
- 缩写的首字母必须与正文
其余的缩写(缩写减去第一个字母)必须是以下的缩写:
- The first letter of the abbreviation must match the first letter ofthe text
The rest of the abbreviation (the abbrev minus the first letter) must be an abbreviation for:
- 剩下的单词,或
- 剩余的文本开始于第一个单词中的任何位置.
tests=(
('fck','fc kopenhavn',True),
('fco','fc kopenhavn',False),
('irl','in real life',True),
('irnl','in real life',False),
('ifk','ifk gotebork',True),
('ifko','ifk gotebork',False),
('aik','allmanna idrottskluben',True),
('aid','allmanna idrottskluben',True),
('manu','manchester united',True),
('fz','faz zoo',True),
('fzz','faz zoo',True),
('fzzz','faz zoo',False),
)
def is_abbrev(abbrev, text):
abbrev=abbrev.lower()
text=text.lower()
words=text.split()
if not abbrev:
return True
if abbrev and not text:
return False
if abbrev[0]!=text[0]:
return False
else:
return (is_abbrev(abbrev[1:],' '.join(words[1:])) or
any(is_abbrev(abbrev[1:],text[i+1:])
for i in range(len(words[0]))))
for abbrev,text,answer in tests:
result=is_abbrev(abbrev,text)
print(abbrev,text,result,answer)
assert result==answer
这篇关于检查字符串是否是名称的可能缩写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!