在列表python中搜索单词的其余部分

时间:2014-07-12 22:02:14

标签: python regex list search

用户将输入一个输入字段。在他们输入的每个字母之后,它将搜索列表中剩下的单词。例如,如果用户键入Arlist = ["Arial","Cat","Pie","Terminal"],则会替换用Arial键入的内容,因为前几个字母匹配。 现在记住我对python相对较新,所以我没有得到正则表达式。我可以处理改变这个词等等。我只是需要帮助搜索列表。

以下是代码:

fonts = ["Arial","Calibri","Cambria","Cambria Math","Candara","Comic Sans MS","Consolas","Constantia","Corbel","Courier","Courier New","Fixedsys","Franklin Gothic","Gabriola","Georgia","Impact","Lucida Console","Lucida Sans Unicode","Modern","MS Sans Serif","MS Serif","Palatino Linotype","Roman","Segoe Print","Segoe Script","Segoe UI","Segoe UI Symbol","Small Fonts","Small Fonts","System","Tahoma","Terminal","Times New Roman","Trebuchet MS","Verdana"]

def findfontname(event):
       #Search list:
       for item in fonts:
           if item == findfont.get(0,END):
               print("Found")

findfont.bind("<Key>", findfontname)

2 个答案:

答案 0 :(得分:0)

您可以使用in检查某些文字是否在任何地方的其他文字中

fonts = ["Arial","Calibri","Cambria","Cambria Math","Candara","Comic Sans MS","Consolas","Constantia","Corbel","Courier","Courier New","Fixedsys","Franklin Gothic","Gabriola","Georgia","Impact","Lucida Console","Lucida Sans Unicode","Modern","MS Sans Serif","MS Serif","Palatino Linotype","Roman","Segoe Print","Segoe Script","Segoe UI","Segoe UI Symbol","Small Fonts","Small Fonts","System","Tahoma","Terminal","Times New Roman","Trebuchet MS","Verdana"]

text = findfont.get(0,END):
text = text.lower()

for item in fonts:
    if text in item.lower():
       print("Found")

如果您搜索以其他文字开头的文字

,则可以使用startswith()
text = findfont.get(0,END):
text = text.lower()

for item in fonts:
    if item.lower().startswith(text):
       print("Found")

答案 1 :(得分:0)

我不知道代码的其余部分是什么样的,但希望我能为您提供一个有用的演示。据我所知,你想检查字体列表中的字符串是否以给定的子字符串开头。

>>> fonts = ["Arial","Calibri","Cambria","Cambria Math"]
>>> sub = 'xYz' # there should be no match for this
>>> sub = sub.lower() # convert to lowercase
>>> [x for x in fonts if x.lower().startswith(sub)]
[]

因此,第一个示例返回一个空列表,该列表在布尔上下文中计算为False

>>> sub = 'Ar'
>>> sub = sub.lower()
>>> [x for x in fonts if x.lower().startswith(sub)]
['Arial']

这会返回一个结果,因此您应该能够显示&#39; Arial&#39;现在。当用户输入以C开头的内容时会出现问题。

>>> sub = 'cA'
>>> sub = sub.lower()
>>> [x for x in fonts if x.lower().startswith(sub)]
['Calibri', 'Cambria', 'Cambria Math']

如您所见,有三种可能的匹配。现在,您的设计决定是显示所有比赛,还是在只有一场比赛之前不显示任何内容。如果你想要后一个选项,你可以发出这样的话:

matches = [x for x in fonts if x.lower().startswith(sub)]
if len(matches) == 1: # exactly one match
    match = matches[0]
    # code to display the match

最后注意事项:如果您的字体列表变大,请考虑将其设为set