我找到了一个单词“plant”的同义词
syn = wordnet.synsets('plant')[0].lemmas()
>>>[Lemma('plant.n.01.plant'), Lemma('plant.n.01.works'), Lemma('plant.n.01.industrial_plant')]
和输入词
word = 'work'
我想找到syn中是否出现'work'。怎么做?
答案 0 :(得分:1)
您可以使用python中的关键字in
轻松检查是否存在子字符串:
>>> word = "work"
>>> word in 'plant.n.01.works'
True
>>> word in 'plant.n.01.industrial_plant'
False
如果你想在列表中测试它,你可以做一个循环:
syn = ["plant.one","plant.two"]
for plant in syn:
if word in plant:
print("ok")
或者更好的列表理解:
result = [word in plant for plant in syn]
# To get the number of matches, you can sum the resulting list:
sum(result)
编辑:如果您要查找多个单词列表,则可以嵌套两个循环:
words_to_search = ["work","spam","foo"]
syn = ["plant.one","plant.two"]
for word in words_to_search_for:
if sum([word in plant for plant in syn]):
print("{} is present in syn".format(word))
请注意,您正在操纵Lemma个对象而不是字符串。如果对象未实现word in plant.name
方法,则可能需要检查word
而不是[__contains__](https://docs.python.org/2/library/operator.html#operator.__contains__)
。我不熟悉这个库。
答案 1 :(得分:1)
Lemma
有一个name()
方法,所以你可以做的是
>>> 'works' in map(lambda x: x.name(), syn)
True
编辑:没有看到你说"工作",不起作用,所以这将是:
>>> for i in syn:
... if 'work' in i.name():
... print True
...
True
例如,您可以将其包装在一个函数中。
或者我提出的两个建议的混合:
any(map(lambda x: 'work' in x, map(lambda x: x.name(), syn)))
答案 2 :(得分:0)
str1 = "this is a example , xxx"
str2 = "example"
target_len = len(str2)
str_start_position = str1.index(str2) #or str1.find(str2)
str_end_position = str_start_position + target_len
您可以使用str_start_position和str_end_position来获取目标子字符串