简体   繁体   English

如何在python中检查字符串中的精确单词

[英]How do I check for an EXACT word in a string in python

Basically I need to find a way to figure out a way to find the EXACT word in a string.基本上我需要找到一种方法来找出在字符串中找到精确单词的方法。 All the information i have read online has only given me how to search for letters in a string so我在网上阅读的所有信息只告诉了我如何在字符串中搜索字母,所以

98787This is correct 98787这是正确的

will still come back as true in an if statement.仍然会在 if 语句中返回为真。

This is what I have so far.这就是我到目前为止所拥有的。

  elif 'This is correct' in text:
    print("correct")

This will work with any combination of letters before the Correct... For example fkrjCorrect, 4123Correct and lolcorrect will all come back as true in the if statement.这将适用于正确之前的任何字母组合...例如,fkrjCorrect、4123Correct 和 lolcorrect 在 if 语句中都将返回为真。 When I want it to come back as true only IF it exactly matches "This is correct"当我希望它仅在它与“这是正确的”完全匹配时才返回真实

You can use the word-boundaries of regular expressions.您可以使用正则表达式的词边界。 Example:例子:

import re

s = '98787This is correct'
for words in ['This is correct', 'This', 'is', 'correct']:
    if re.search(r'\b' + words + r'\b', s):
        print('{0} found'.format(words))

That yields:这产生:

is found
correct found

EDIT : For an exact match, replace \\b assertions with ^ and $ to restrict the match to the begin and end of line.编辑:对于完全匹配,用^$替换\\b断言以将匹配限制为行的开头和结尾。

Use the comparison operator == instead of in then:使用比较运算符==而不是in then:

if text == 'This is correct':
    print("Correct")

This will check to see if the whole string is just 'This is correct' .这将检查整个字符串是否只是'This is correct' If it isn't, it will be False如果不是,它将是False

Actually, you should look for 'This is correct' string surrounded by word boundaries.实际上,您应该寻找被单词边界包围的“这是正确的”字符串。

So所以

import re

if re.search(r'\bThis is correct\b', text):
    print('correct')

should work for you.应该为你工作。

I suspect that you are looking for the startswith() function.我怀疑您正在寻找startswith()函数。 This checks to see if the characters in a string match at the start of another string这会检查字符串中的字符是否与另一个字符串的开头匹配

"abcde".startswith("abc") -> true

"abcde".startswith("bcd") -> false

There is also the endswith() function, for checking at the other end.还有endswith()函数,用于检查另一端。

You can make a few changes.您可以进行一些更改。

elif 'This is correct' in text[:len('This is correct')]:

or要么

elif ' This is correct ' in ' '+text+' ':

Both work.两者都有效。 The latter is more flexible.后者更灵活。

Below is a solution without using regular expressions.以下是不使用正则表达式的解决方案。 The program searches for exact word in this case 'CASINO' and prints the sentence.程序在本例中搜索确切的单词“CASINO”并打印句子。

    words_list = [ "The Learn Python Challenge Casino.", "They bought a car while at 
    the casino", "Casinoville" ]
    search_string = 'CASINO'
    def text_manipulation(words_list, search_string):
        search_result = []
        for sentence in words_list:
            words = sentence.replace('.', '').replace(',', '').split(' ')
            [search_result.append(sentence) for w in words if w.upper() == 
              search_string]
        print(search_result)

    text_manipulation(words_list, search_string)

This will print the results - ['The Learn Python Challenge Casino.', 'They bought a car while at the casino']这将打印结果 - ['The Learn Python Challenge Casino.', '他们在赌场买了一辆车']

Break up the string into a list of strings with .split() then use the in operator.使用 .split() 将字符串分解为字符串列表,然后使用 in 运算符。

This is much simpler than using regular expressions.这比使用正则表达式简单得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查另一个字符串中是否存在确切的字符串? - How do I check for if an exact string exists in another string? 如何使用python从文本中提取准确的单词? - How do I extract an exact word from text by using python? 如何使用 python 在字符串中找到确切的字符串 - How do i find an exact string within a string using python Python - 如何突出显示字符串中的单词? - Python - How do I highlight a word in a string? 如何在Python中找到文件行中的确切字符串? - How do I find an exact string in the line of a file in Python? 如何检查用户给定输入的字符串是否等于 Python 中的某个字母/单词 - How do I check if a string with a user given input is equal to a certain letter/ word in Python 如何找到在单词搜索中找到的单词的确切位置 - How do I find the exact location of the word that is found in the word search 如何检查 Python 中的单词(甚至计算重复的字母)? - How do I check for a word ( even counting duplicated letters ) in Python? 如何将字符串中出现的所有单词“I”大写? Python - How do I capitalize all occurrences of the word 'I' in a string? Python 仅当与其他字符隔开时,如何检查行中的确切字符串? - How do I check for an exact string in a line only when it's spaced out from other characters?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM