簡體   English   中英

在一個句子中而不是一個單詞中找到一個單詞(python)

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

在Python中,im嘗試使用以下命令在句子中查找單詞:

if word in sentence:
    number = number + 1

這對於在句子中查找單詞是很好的工作,我遇到的問題是該代碼在其他單詞中找到了單詞。 例如:

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

數字將等於2而不是1,因為“ or”在“ Python”之后和“ Java”之前,並且它還在單詞“ word”中找到“ or”,而Im試圖找到一種方法來僅通過以下方式找到單詞“ or”本身,而不是程序在句子和另一個單詞中找到它。

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

應該這樣做。

lower將所有文本轉換為小寫,split將其轉換為列表(空格是默認的定界符),然后count對列表進行計數。

您需要先使用str.split拆分句子:

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

這將為您提供單詞列表。 之后,您的代碼將起作用:

>>> # 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
>>>

您可以嘗試先拆分 sentence ,這樣

if word in sentence.split(" "):

假設所有單詞都用一個空格隔開,這會將sentence拆分成單詞數組。 這相當於使用

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

這將檢查整個單詞是否存在於列表中,而不是檢查原始sentence子字符串

暫無
暫無

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

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