简体   繁体   English

在Python中查找子字符串

[英]Find substring in Python

I have found synonyms of a word "plant" 我发现一个词“植物”的同义词

syn = wordnet.synsets('plant')[0].lemmas()
>>>[Lemma('plant.n.01.plant'), Lemma('plant.n.01.works'), Lemma('plant.n.01.industrial_plant')]

and an input word 和一个输入词

word = 'work'

I want to find if 'work' appears in syn. 我想查找“工作”是否出现在syn中。 How to do it? 怎么做?

You can easily check for the presence of a substring using the keyword in in python: 你可以很容易地检查使用关键字的子存在in在python:

>>> word = "work"
>>> word in 'plant.n.01.works'
True
>>> word in 'plant.n.01.industrial_plant'
False

If you want to test this in a list you can do a loop: 如果要在列表中对此进行测试,可以执行循环:

syn = ["plant.one","plant.two"]
for plant in syn:
    if word in plant:
        print("ok")

Or better a list comprehension: 或更好的列表理解:

result = [word in plant for plant in syn]
# To get the number of matches, you can sum the resulting list:
sum(result)

Edit : If you have a long list of words to look for, you can just nest two loops: 编辑 :如果要查找的单词很长,则可以嵌套两个循环:

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

Note that you are manipulating Lemma objects and not strings. 请注意,您在操纵引理对象而不是字符串。 You might need to check for word in plant.name instead of just word if the object do not implement the [__contains__](https://docs.python.org/2/library/operator.html#operator.__contains__) method. 如果对象未实现[__contains__](https://docs.python.org/2/library/operator.html#operator.__contains__)方法,则可能需要检查word in plant.nameword而不是word I am not familiar with this library though. 我对这个图书馆不熟悉。

Lemma 's have a name() method so what you could do is Lemma有一个name()方法,所以您可以做的是

>>> 'works' in map(lambda x: x.name(), syn)
True

Edit: did not see you said "work", not works, so this would be: 编辑:没有看到您说的“工作”,没有工作,所以这将是:

>>> for i in syn:
...     if 'work' in i.name():
...             print True
... 
True

You can wrap it in a function for example. 例如,您可以将其包装在一个函数中。

Or a mixture of the two suggestions I made: 或我提出的两个建议的混合:

any(map(lambda x: 'work' in x, map(lambda x: x.name(), syn)))
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

you can use str_start_position and str_end_position to get your target substring 您可以使用str_start_position和str_end_position来获取目标子字符串

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

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