使用grep在特定上下文中查找字符串

2024-09-30 18:15:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从一个大文件中找到并提取被特定上下文包围的所有单词。文件中的所有行看起来都是这样的,但是在><\w>之间有不同的单词:

<="UO" lemma="|" lex="|" sense="|" prefix="|" suffix="|" compwf="|" complemgram="|" ref="05" dephead="04" deprel="ET">and<\w>

我只希望输出是'和'。所以我基本上想提取上下文>xxx<\w>中的所有字符串(单词、标点和数字)。我用grep和regex尝试了很多不同的选择,但是我要么得到所有的单词,要么得到><\w>的模式。。。从整个文件中,我希望输出如下所示:

and 
we
appreciate
this
very 
much
.

等等。。。你知道吗


Tags: and文件refprefix单词suffixetlex
2条回答

好的。给定具有以下值的输入文件(我希望了解您的用例):

<="UO" lemma="|" lex="|" sense="|" prefix="|" suffix="|" compwf="|" complemgram="|" ref="05" dephead="04" deprel="ET">and<\w>
<="UO" lemma="|" lex="|" sense="|" prefix="|" suffix="|" compwf="|" complemgram="|" ref="05" dephead="04" deprel="ET">we<\w>
<="UO" lemma="|" lex="|" sense="|" prefix="|" suffix="|" compwf="|" complemgram="|" ref="05" dephead="04" deprel="ET">appreciate<\w>
<="UO" lemma="|" lex="|" sense="|" prefix="|" suffix="|" compwf="|" complemgram="|" ref="05" dephead="04" deprel="ET">this<\w>
<="UO" lemma="|" lex="|" sense="|" prefix="|" suffix="|" compwf="|" complemgram="|" ref="05" dephead="04" deprel="ET">very<\w>
<="UO" lemma="|" lex="|" sense="|" prefix="|" suffix="|" compwf="|" complemgram="|" ref="05" dephead="04" deprel="ET">much<\w>
<="UO" lemma="|" lex="|" sense="|" prefix="|" suffix="|" compwf="|" complemgram="|" ref="05" dephead="04" deprel="ET">.<\w>

下面的python regex应该适合您:

>>> import re
>>> pat = re.compile(r'(?<=">)(.*)(?=<\\w>)')
>>> pat.findall(input_string)
['and', 'we', 'appreciate', 'this', 'very', 'much', '.']

你可以用这样的图案。这将匹配><\w>之间的任何内容。你知道吗

import re
pat = re.compile(r'>(.*?)<\\w>')
pat.findall(input_string)

相关问题 更多 >