【发布时间】:2011-12-10 16:03:14
【问题描述】:
如何在搜索列表时匹配精确的字符串/单词。我试过了,但它不正确。下面我给出了示例列表、我的代码和测试结果
list = ['Hi, friend', 'can you help me?']
我的代码
dic=dict()
for item in list:
for word in item.split():
dic.setdefault(word, list()).append(item)
print dic.get(s)
测试结果:
s = "can" ~ expected output: 'can you help me?' ~ output I get: 'can you help me?'
s = "you" ~ expected output: *nothing* ~ output I get: 'can you help me?'
s = "Hi," ~ expected output: 'Hi, friend' ~ output I get: 'Hi, friend'
s = "friend" ~ expected output: *nothing* ~ output I get: 'Hi, friend'
我的列表包含 1500 个字符串。有人可以帮帮我吗??
【问题讨论】:
-
您需要更具体地了解精确匹配的含义。你的意思是它必须以一个特定的词开头?这个词必须在字符串中的某个地方?
-
你的问题不是很清楚。您要问的是
How to match exact string/word while searching a list.,但从您的示例中,我了解到您只是在搜索前缀匹配,即您正在搜索的单词是否是短语中的第一个单词。 -
嗨 Abhijit,我想要前缀匹配。示例:字符串“你能帮帮我吗?”
-
如果我们搜索“Can”,我们需要得到“can you help me??”否则不需要匹配任何东西。你能得到它阿比吉特吗??
-
看看我的例子或 Anurag 的例子。哪一种适合你,你可以随它去..
标签: python