在Python中仅匹配精确单词/字符串
如何在搜索列表时匹配准确的字符串或单词。我尝试过,但结果不正确。下面我给出了一个示例列表、我的代码和测试结果。
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个字符串。有人能帮我吗??
2 个回答
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
看起来你需要一个句子和它的第一个单词的映射,这样你就不需要把句子里的所有单词都映射,只需要第一个单词就可以了。
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
。 - 使用默认字典,这样可以直接往字典里添加条目,而不需要先添加一个默认条目。
- 用更具描述性的名字,而不是 mylist 或 dic。