Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Grep文本文件中的一系列单词_Python_Word_Range_Text Files - Fatal编程技术网

Python Grep文本文件中的一系列单词

Python Grep文本文件中的一系列单词,python,word,range,text-files,Python,Word,Range,Text Files,我有一个文本文件,我的目标是生成一个输出文件,其中包含两个特定单词之间的所有单词 例如,如果我有以下文本: askdfghj... Hello world my name is Alex and I am 18 years all ...askdfgj. 我想知道“我的”和“亚历克斯”之间的所有单词 输出: my name is Alex my name is Alex 我有这个想法。。。但我不知道如何创建范围: if 'my' in open(out).read(): w

我有一个文本文件,我的目标是生成一个输出文件,其中包含两个特定单词之间的所有单词

例如,如果我有以下文本:

askdfghj... Hello world my name is Alex and I am 18 years all ...askdfgj.
我想知道“我的”和“亚历克斯”之间的所有单词

输出:

my name is Alex
my name is Alex
我有这个想法。。。但我不知道如何创建范围:

if 'my' in open(out).read():
        with open('results.txt', 'w') as f:
            if 'Title' in open(out).read():
                f.write('*')
        break

我想要一个带有“我的名字是Alex”的输出文件。

您可以在这里使用
regex

>>> import re
>>> s = "askdfghj... Hello world my name is Alex and I am 18 years all ...askdfgj."
>>> re.search(r'my.*Alex', s).group()
'my name is Alex'
如果字符串在
my
之后包含多个
Alex
,并且您只需要最短的匹配,则使用
*?

使用

>>> s = "my name is Alex and you're Alex too."
>>> re.search(r'my.*?Alex', s).group()
'my name is Alex'
>>> re.search(r'my.*Alex', s).group()
"my name is Alex and you're Alex"
没有

>>> s = "my name is Alex and you're Alex too."
>>> re.search(r'my.*?Alex', s).group()
'my name is Alex'
>>> re.search(r'my.*Alex', s).group()
"my name is Alex and you're Alex"
代码:

with open('infile') as f1, open('outfile', 'w') as f2:
    data = f1.read()
    match = re.search(r'my.*Alex', data, re.DOTALL)
    if match:
        f2.write(match.group())

您可以使用正则表达式
my.*Alex

data = "askdfghj... Hello world my name is Alex and I am 18 years all ...askdfgj"
import re
print re.search("my.*Alex", data).group()
输出