【问题标题】:Find string in specific context using grep使用 grep 在特定上下文中查找字符串
【发布时间】:2017-04-05 14:16:27
【问题描述】:

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

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

我只希望输出是“和”。所以我基本上想提取上下文&gt;xxx&lt;\w&gt;中的所有字符串(单词、标点符号和数字)。我用 grep 和 regex 尝试了一堆不同的替代方案,但我要么用&gt;&lt;\w&gt; 得到所有单词或模式......从整个文件中,我希望输出看起来像这样:

and 
we
appreciate
this
very 
much
.

等等……

【问题讨论】:

  • 添加输入文本和预期输出
  • 抱歉,由于某种原因,我第一次发帖时没有显示
  • “我只希望输出为 'and'”不足以解释您要达到的目标。请给我们一个输出应该是什么样子的例子;否则,我的建议是使用此代码:echo "and"
  • 我想,输入文本中必须有单词we appreciate this very much。更新您的输入
  • 那么,您想将文件中的所有单词、标点符号和数字分成不同的行吗?就这些?

标签: python regex grep


【解决方案1】:

您可以使用这样的模式。这将匹配 &gt;&lt;\w&gt; 之间的任何内容。

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

【讨论】:

  • 您的模式不会从所需结果中排除 &gt;&lt;\w&gt; 字符集
【解决方案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 正则表达式应该适合你:

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

【讨论】:

  • 您的模式将无法使用标点符号。就像最后的.
  • 如果中间有&gt;怎么办?喜欢&gt;&gt;&lt;\w&gt;
  • 你在编辑器中测试过吗?那没有什么区别。 .* 捕获任何类型的字符, (?=) 显式查找 以关闭匹配上下文。唯一可能使其中断的是匹配区域内的上下文字符串实际上是字符串 并且由于某种原因匹配看起来像:&gt;&lt;\w&gt;&lt;\w&gt;
  • @salmanwahed,好的,如果您认为这是一个问题,那么可以通过在第一个 match but don't include 大括号中添加 " 来避免这种情况,就像 (?&lt;="&gt;) 一样,更新了我的答案
猜你喜欢
  • 2013-10-20
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 2014-07-23
  • 1970-01-01
  • 2013-08-19
相关资源
最近更新 更多