簡體   English   中英

在python中只匹配精確的單詞/字符串

[英]match only exact word/string in 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個字符串。 有誰可以幫幫我?

如果您只是想查看句子是否以給定的單詞開頭,您可以嘗試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

看起來你需要一個句子地圖和他們的起始單詞,所以你不需要映射那個句子中的所有單詞而只需要映射第一個單詞。

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

還要注意上面代碼中的一些內容

  1. 不要使用名稱list作為變量名稱,因為python將其用於list class
  2. 使用默認dict可以直接將條目添加到字典而不是首先添加默認條目
  3. 更好的描述性名稱而不是mylist或dic

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM