使用Python匹配用户输入列表中的类似项目?

时间:2018-05-04 23:35:36

标签: python regex matching

我对Python很新,而且在其他任何事情之前,如果标题不够具体,我还是要道歉,但我不知道另一种说法。此外,如果这个问题是重复的,请道歉。正如我所说,我真的不知道该寻找什么。无论如何,这就是我想要做的事情:

我有一个这样的列表:names = ['william shakespeare', 'shakira', 'tom ford', 'tim ford']

我希望用户能够输入一个名字,所以我会使用name = input('Enter name:'),这就是我被卡住的地方。我希望用户能够输入类似shak的字符串,并让程序显示1. William Shakespeare 2. Shakira,或者如果用户将ford放入程序显示1. Tom Ford 2. Tim Ford,并且用户更具体,例如:shakespeare只让节目显示1. William Shakespeare

我认为这是一个正则表达式问题,但我觉得正则表达式非常混乱。我试过看几个视频都无济于事。任何类型的帮助表示赞赏。提前谢谢!

6 个答案:

答案 0 :(得分:0)

这对你有用吗?如果输出不是你想要的那样,我希望你以后可以处理那个部分。逻辑找到每个适用的名称。

names = ['william shakespeare', 'shakira', 'tom ford', 'tim ford']
while True:
    name = input('Enter name: ')
    print([entry for entry in names if name in entry])

答案 1 :(得分:0)

在我看来,正则表达式会有点矫枉过正。您可以使用for循环遍历列表。然后使用in运算符,您可以检查输入的字符串是否在字符串中(称为子字符串)。我举一个简单的例子。

names = ['william shakespeare', 'shakira', 'tom ford', 'tim ford']

substring = input('Enter a substring: ')

for name in names:
    if (substring in name):
        print(name)

既然你说你是python的新手我没有使用列表推导或任何复杂的东西。

答案 2 :(得分:0)

你可以尝试这样的事情。

list = ['william shakespeare', 'shakira', 'tom ford', 'tim ford']

def get_matching_term(input, list):
    matches = []
    for word in list:
        if input.lower() in word.lower():
            matches.append(word)
    return matches

thing_to_match = raw_input("Enter name to find:")
matches = get_matching_term(thing_to_match, list)

for idx, match in enumerate(matches):
    print("Match #" + str((idx + 1)) + ": " + match)

然后你可以像这样调用它。

python test.py
Enter name to find: shak
Match #1: william shakespeare
Match #2: shakira

答案 3 :(得分:0)

names = ['william shakespeare', 'shakira', 'tom ford', 'tim ford']

search = str(input("Please enter search term  "))

ref = list(search.lower()) # this is your search text

out = []

count = 1

ind = 0


for i in names: # loops over your list

        #print () #take the hash out to see what is i

        for j in list(i.lower()): # list converts your variable into a list ie shakira = ['s','h'..]

            if j == ref[ind]:
                ind += 1
            else:
                ind = 0  

            if ind == len(ref): #ind is gonna go over each index in ref, if ind = the length of your 
        # search text then you have found a match

                out.append(i)
                ind = 0
                break


if len(out) == 0:
    out.append(" Nothing found ")
    count = 0

for i in out:
    print ("{}. {}".format(count,i), end = "\t\t")
    count += 1

好!有很多方法可以做到这一点,试图让它尽可能简单。 缺陷:如果有两个相似的名字,例如威尔和威廉,你搜索遗嘱,你将得到两个名字。如果您搜索威廉,它将只给您Willaim。此外,设计效率不高,两个for循环,基本上它与列表中的字母数量成线性关系(总字母数。)看看它是怎么回事。

答案 4 :(得分:0)


dict_list = [{"First_Name": "Sam", "Last_Name": "John", "Age": 24},
            {"First_Name": "Martin", "Last_Name": "Lukas", "Age": 34},
            {"First_Name": "Jeff", "Last_Name": "Mark", "Age": 44},
            {"First_Name": "Jones", "Last_Name": "alfred", "Age": 54}]

getdetails = input("Name: ")

for i in range(len(dict_list)):
    if (getdetails in dict_list[i]["First_Name"]):
        print(f'Details are  {dict_list[i]}')

$$$$$$$ output $$$$$$

Name: Jeff
Details are  {'First_Name': 'Jeff', 'Last_Name': 'Mark', 'Age': 44}

Process finished with exit code 0 

答案 5 :(得分:-1)

正则表达式非常有用,但这个特殊的例子不需要正则表达式。在两个字符串上使用string.lower()会使这种情况不敏感。

i=0
For item in names:
  if name.lower() in item.lower():
    i++
    print str(i) + '. ' + item
相关问题