简体   繁体   English

在一个句子中而不是一个单词中找到一个单词(python)

[英]Finding a word in just a sentence and not in a word (python)

In Python im trying to find a word in a sentece by using: 在Python中,im尝试使用以下命令在句子中查找单词:

if word in sentence:
    number = number + 1

This works fine for finding a word in a sentence, the problem im running into is that this code finds the word inside other words. 这对于在句子中查找单词是很好的工作,我遇到的问题是该代码在其他单词中找到了单词。 For example: 例如:

word = "or"
sentence = "Python or Java use a lot of words"
if word in sentence:
    number = number + 1

number will equal 2 instead of 1 because "or" is after "Python" and before "Java", and it also finds "or" in the word "word" Im trying to find a way to find just the word "or" by itself, instead of the program finding it in the sentence and in another word. 数字将等于2而不是1,因为“ or”在“ Python”之后和“ Java”之前,并且它还在单词“ word”中找到“ or”,而Im试图找到一种方法来仅通过以下方式找到单词“ or”本身,而不是程序在句子和另一个单词中找到它。

"Python or Java use a lot of words".lower().split().count('or')

should do it. 应该这样做。

lower converts all of the text to lower case, split turns it into a list (space is the default delimiter) then count does a count against the list. lower将所有文本转换为小写,split将其转换为列表(空格是默认的定界符),然后count对列表进行计数。

You need to split the sentence first using str.split : 您需要先使用str.split拆分句子:

>>> sentence = "Python or Java use a lot of words"
>>> sentence.split()
['Python', 'or', 'Java', 'use', 'a', 'lot', 'of', 'words']
>>>

This will give you a list of the words. 这将为您提供单词列表。 After that, your code will work: 之后,您的代码将起作用:

>>> # I made this so I didn't get a NameError
>>> number = 0
>>> word = "or"
>>> sentence = "Python or Java use a lot of words"
>>> if word in sentence.split():
...     # This is the same as "number = number + 1"
...     number += 1
...
>>> number
1
>>>

You can try splitting the sentence first, as so 您可以尝试先拆分 sentence ,这样

if word in sentence.split(" "):

This will split sentence into an array of words, assuming all the words are separated by a single space. 假设所有单词都用一个空格隔开,这会将sentence拆分成单词数组。 This is equivalent to using 这相当于使用

if word in [ "Python", "or", "Java", "use", "a", "lot", "of", "words" ]:

which will check if the whole word exists in the list, rather than checking for substrings in the original sentence 这将检查整个单词是否存在于列表中,而不是检查原始sentence子字符串

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM