[英]Finding Similarity between 2 sentences using word2vec of sentence with 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.