Как найти слова, которые могут следовать за одним словом в большой строке в Python.? - PullRequest
0 голосов
/ 25 апреля 2018
str1=""”Python is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991. An interpreted language, Python has a design philosophy which emphasizes code readability (notably using whitespace indentation to delimit code blocks rather than curly braces or keywords), and a syntax which allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. The language provides constructs intended to enable writing clear programs on both a small and large scale .Python features a dynamic type system and automatic memory management and supports multiple programming paradigms, including object-oriented, imperative, functional programming, and procedural styles. It has a large and comprehensive standard library. Python interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. CPython, the reference implementation of Python, is open source software and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation."""..

вывод должен быть:

python : [is, has, features, interpreters, code, Software

Ответы [ 2 ]

0 голосов
/ 25 апреля 2018

Для этого можно использовать генератор:

def yielder(x, value='Python'):
    match = False
    for word in x.split():
        if match == True:
            yield word
            match = False
        if word == value:
            match = True

res = list(yielder(str1))

['is', 'has', 'interpreters', 'code', 'Software']

Преимущество этого метода в том, что он ленивый после разбиения .Для длинных строк вы можете извлекать результаты во время итерации.

Чтобы узнать больше, посмотрите следующее:

  • Генераторы: как работает оператор yield
  • Сплит строки: как str.split работает
0 голосов
/ 25 апреля 2018

Вы можете использовать регулярное выражение для поиска слов, следующих за словом python, например,

>>> import re
>>> re.findall(r'Python (\w+)', s)
['is', 'has', 'features', 'interpreters', 'code', 'is', 'Software']

Поскольку этот список может содержать дубликаты, вы можете создать set, если вы хотите набор уникальных слов

>>> set(re.findall(r'Python (\w+)', s))
{'Software', 'is', 'has', 'interpreters', 'code', 'features'}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...