使用python进行提取和解析

时间:2013-03-16 22:15:41

标签: python parsing

我有两行格式为

VP VB go
NP PRP$ your NN left

保存在文本文件中。 我想访问此文本文件,然后在新文本文件中打印以下结果

NP NN left

使用python帮助我如何做到这一点。

感谢您提前提供任何帮助

2 个答案:

答案 0 :(得分:1)

如果我正确地解释你,你想要所有的

案例
NP NN word

在这种情况下,您可以使用正则表达式查找NP,NN和后续单词:

import re
f = open('file.txt')
regex = r'^(NP).*?(NN) (\w+).*?$'
for line in f:
    try: ' '.join(re.search(regex, line).groups())
    except AttributeError: pass

答案 1 :(得分:0)

编辑:这样更好吗?

f=open("myfile")
#read all lines of the file and remove newline characters
a=[i.strip() for i in f.readlines()]
f.close()

for i in a:
  i=i.split()
  n=-1
  try:
    n=i.index("NN")
  except:
    pass
  if n!=-1 and n!=len(i)-1 and i[0]=="NP":
    print i[0], i[n], i[n+1]