如何在文件中从and到关键字中搜索特定词并在python中打印句子

时间:2018-09-20 15:27:25

标签: python regex file search

我正在尝试获取文件作为输入并搜索特殊字符。 我从和给键作为输入。 如果to关键字在下一行中,则应打印到找到to关键字为止。

ln -Fs `find /usr/local -name "MacVim.app"` /Applications/MacVim.app

说我有一个文件:

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($myfqfilenamehere);
$tags = $templateProcessor->getVariables();
foreach($tags as $tag){
    $templateProcessor->setValue($tag, "a value here");
}

通过使用上面的代码,我得到的输出如下:

for line in contents:

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

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

我的另一个目标是我应该打印 ['new','[/]','friend','[//]','rere','bch','/ [] /''new''there''。]

2 个答案:

答案 0 :(得分:1)

对于任意文本,您可以使用正则表达式:

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

要消除星号:

>>> [s.replace("*", "") for s in re.findall("\*[^/*]*\*", text)]
['foo', 'foobar']

答案 1 :(得分:1)

如果您可以读取文件并将其转换为字符串。 我们可以使用

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