在字符串中寻找单个确切单词

时间:2019-06-19 16:28:52

标签: python python-3.x

我正在尝试在一个大字符串中找到一个准确的单词。

我尝试了以下方法:

for word in words:
    if word in strings:
        best.append("The word " + word + " The Sentence " + strings)
    else:
        pass

这似乎起初是可行的,直到尝试在更大的字符串中使用更大的单词集并获得部分匹配。作为一个例子,如果单词是“我”,它将被发现时忽略“消息”。

有没有一种方法可以精确地搜索“我”?

谢谢。

7 个答案:

答案 0 :(得分:2)

您需要设置边界才能找到完整的单词。我去正则表达式。像这样:

re.search(r'\b' + word_to_find + r'\b')

答案 1 :(得分:1)

您可以将字符串拆分为单词,然后执行in操作,确保删除列表中的单词和所有尾随空格的字符串

import string

def find_words(words, s):
    best = []

    #Strip extra whitespaces if any around the word and make them all lowercase
    modified_words = [word.strip().lower() for word in words]

    #Strip away punctuations from string, and make it lower
    modified_s = s.translate(str.maketrans('', '', string.punctuation))
    words_list = [word.strip().lower() for word in modified_s.lower().split()]

    #Iterate through the list
    for idx, word in enumerate(modified_words):
        #If word is found in lit of words, append to result
        if word in words_list:
            best.append("The word " + words[idx] + " The Sentence " + s)

    return best

print(find_words(['me', 'message'], 'I me myself'))
print(find_words(['   me    ', 'message'], 'I me myself'))
print(find_words(['me', 'message'], 'I    me    myself'))
print(find_words(['me', 'message'], 'I am me.'))
print(find_words(['me', 'message'], 'I am ME.'))
print(find_words(['Me', 'message'], 'I am ME.'))

输出将为

['The word me The Sentence I me myself']
['The word    me     The Sentence I me myself']
['The word me The Sentence I    me    myself']
['The word me The Sentence I am me.']
['The word me The Sentence I am ME.']
['The word Me The Sentence I am ME.']

答案 2 :(得分:1)

您还可以使用正则表达式精确查找单词。 \\ b表示边界,例如空格或标点符号。

for word in words:
    if len(re.findall("\\b" + word + "\\b", strings)) > 0:
        best.append("The word " + word + " The Sentence " + strings)
    else:
        pass

双反斜杠归因于'\b'字符是退格控制序列。 Source

答案 3 :(得分:0)

您可以在if语句中包括周围的空格。

function isPlaying(){
   if(sound.playing()){
      console.log('audio is currently playing...');
      setTimeout(isPlaying, 1000); //adjust timeout to fit your needs
   }
}

sound = new Howl({
   src: ['output.mp3'],
   html5: true,
   onplay: isPlaying
});

答案 4 :(得分:0)

要确保您没有检测到包含在单词中的单词(例如“消息”或“ flame”中的“我”),请在检测到的单词前后添加空格。最简单的方法是替换

if word in strings:

if " "+word+" " in strings:

希望这会有所帮助! -西奥

答案 5 :(得分:0)

您需要为搜索设置边界,export class Model { firstName:String lastName:String } 是边界字符。

\b

该字符串包含import re string = 'youyou message me me me me me' print(re.findall(r'\bme\b', string)) message,我们只需要显式地使用me。因此,在搜索表达式中增加了边界。结果如下-

me

了解所有我,但没有['me', 'me', 'me', 'me', 'me'] ,其中也包含message

答案 6 :(得分:0)

在不了解其余代码的情况下,我建议的最佳选择是使用==获得直接匹配,例如

a = 0
list = ["Me","Hello","Message"]
b = len(list)
i = input("What do you want to find?")
for d in range(b):
    if list[a] == i:
        print("Found a match")
    else:
        a = a+1
相关问题