如何在搜索列表时匹配完整的字符串/单词。我试过了,但不正确。下面我给出了样本列表,我的代码和测试结果
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个字符串。任何人都可以帮助我??
答案 0 :(得分:1)
如果你只是想看看句子是否以给定的单词开头,你可以试试startswith
如果你不想;你想要搜索的单词是在单词边界或split()[0]
如果你想要它匹配单词边界。作为一个例子
>>> def foo(s): # @ word boundary
return [x for x in l if x.split()[0]==s]
>>> def bar(s): # Prefix
return [x for x in l if x.startswith(s)]
同样避免覆盖python全局名称空间,就像将列表命名为list
时所做的那样。我在我的例子中称它为l
。
答案 1 :(得分:1)
看起来你需要一个句子地图和他们的起始单词,所以你不需要映射那个句子中的所有单词而只需要映射第一个单词。
from collections import defaultdict
sentences = ['Hi, friend', 'can you help me?']
start_sentence_map = defaultdict(list)
for sentence in sentences:
start = sentence.split()[0]
start_sentence_map[start].append(sentence)
for s in ["can", "you", "Hi,", "friend"]:
print s,":",start_sentence_map.get(s)
输出:
can : ['can you help me?']
you : None
Hi, : ['Hi, friend']
friend : None
还要注意上面代码中的一些内容
list
作为变量名称,因为python将其用于list class