如何在Python中找到单词旁边的单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17686809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:54:49  来源:igfitidea点击:

How to find word next to a word in Python

pythonpython-2.7

提问by Vamsi Varanasi

I would like to find an occurrence of a word in Python and print the word after this word. The words are space separated.

我想在 Python 中找到一个词的出现并在这个词之后打印这个词。单词是空格分隔的。

example :

例子 :

if there is an occurrence of the word "sample" "thisword" in a file . I want to get thisword. I want a regex as the thisword keeps on changing .

如果文件中出现单词“sample”“thisword”。我想得到这个词。我想要一个正则表达式,因为 thisword 不断变化。

采纳答案by crasic

python strings have a built in method split that splits the string into a list of words delimited by white space characters (doc), it has parameters for controlling the way it splits the word, you can then search the list for the word you want and return the next index

python 字符串有一个内置方法 split 将字符串拆分为由空格字符 ( doc)分隔的单词列表,它具有用于控制拆分单词方式的参数,然后您可以在列表中搜索您想要的单词和返回下一个索引

your_string = "This is a string"
list_of_words = your_string.split()
next_word = list_of_words[list_of_words.index(your_search_word) + 1]

回答by Vasilis

A very simple approach:

一个非常简单的方法:

s = "this is a sentense"
target = "is"
words = s.split()
for i,w in enumerate(words):
    if w == target:
        # next word
        print words[i+1]
        # previous word
        if i>0:
            print words[i-1]

回答by AnnaRaven

Sounds like you want a function.

听起来你想要一个函数。

>>> s = "This is a sentence"
>>> sl = s.split()
>>> 
>>> def nextword(target, source):
...   for i, w in enumerate(source):
...     if w == target:
...       return source[i+1]
... 
>>> nextword('is', sl)
'a'
>>> nextword('a', sl)
'sentence'
>>> 

Of course, you'll want to do some error checking (e.g., so you don't fall off the end) and maybe a while loop so you get all the instances of the target. But this should get you started.

当然,你会想要做一些错误检查(例如,这样你就不会从结尾处掉下来),也许还有一个 while 循环,这样你就可以获得目标的所有实例。但这应该让你开始。