1

私はフォーマットにこれらの2行を持っています

VP VB go
NP PRP$ your NN left

テキストファイルに保存されます。このテキスト ファイルにアクセスして、次の結果を新しいテキスト ファイルに出力したい

NP NN left

Pythonを使用してこれを行う方法を教えてください。

事前に助けてくれてありがとう

4

2 に答える 2

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
于 2013-03-16T23:02:01.330 に答える
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]
于 2013-03-16T22:46:19.360 に答える