как найти конкретное ключевое слово from и to в файле и напечатать предложение на python - PullRequest
0 голосов
/ 20 сентября 2018

Я пытаюсь получить файл для ввода и поиска специального символа.Я даю от и до клавиш в качестве ввода.если ключевое слово to находится в следующей строке, я должен напечатать, пока ключевое слово to не будет найдено.

for line in contents:

if line.startswith("*CHI: ") :

       line = line.strip("*")
       tokenize = line.split()
       p.token_filter(tokenize)

скажем, у меня есть файл:

       *CHI: (hi) new [/] friend [//] there [/-] [ bch] [ bch ] /[]/ [/=]
<new>
<there>.
%mod: hi there.
*CHI: <dude>
<there>
*CHI: &=sighs <and instead the> [//] and then the gira?e got it and gave it to the elephant . 
*CHI: <he> [/] <he> [/] he hold it .
*CHI: then [/-] the doctor give the [/] money to the man
*CHI: and (i)s then (.) the little (.) gira?e is crying because it (i)s sinking

Используя приведенный выше код, яполучить вывод следующим образом:

['new', '[/]', 'friend', '[//]', 'there', 'bch', '/[]/']
['dude', 'dude']
['and', 'and', 'instead', 'the', 'the', '[//]', 'and', 'then', 'the', 'gira?e', 'got', 'it', 'and', 'gave', 'it', 'to', 'the', 'elephant', '.']
['he', 'he', '[/]', 'he', 'he', '[/]', 'he', 'hold', 'it', '.']
['then', 'the', 'doctor', 'give', 'the', '[/]', 'money', 'to', 'the', 'man']
['and', 'then', '(.)', 'the', 'little', '(.)', 'gira?e', 'is', 'crying', 'because', 'it', 'sinking']

Моя другая цель - я должен напечатать ['new', '[/]', 'friend', '[//]', 'there', 'bch',' / [] / '' new '' there ''. ']

Ответы [ 2 ]

0 голосов
/ 20 сентября 2018

Если вы можете прочитать файл и преобразовать его в строку.Мы можем использовать

string = "123123STRINGabcabc"

def find_between( string, first, last ):
    try:
        start = string.index( first ) + len( first )
        end = string.index( last, start )
        return string[start:end]
    except ValueError:
        return ""

print find_between( string, "123", "abc" )

т

123STRING
0 голосов
/ 20 сентября 2018

для произвольного текста вы можете использовать регулярное выражение:

>>> import re
>>> text = "*foo* bar *foobar*"
>>> re.findall("\*[^/*]*\*", text)
['*foo*', '*foobar*']

Чтобы избавиться от звездочек:

>>> [s.replace("*", "") for s in re.findall("\*[^/*]*\*", text)]
['foo', 'foobar']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...