Python NLTK は初めてなので、アドバイスが必要です。自分のtxtファイルを開き、単語を正規表現に置き換えるなどの前処理を行いたいです。NLTK 2.0クックブックのようにやろうとしました
import re
replacement_patterns = [
(r'won\'t', 'will not'),
(r'can\'t', 'cannot'),
(r'i\'m', 'i am'),
(r'ain\'t', 'is not'),
(r'(\w+)\'ll', '\g<1> will'),
(r'(\w+)n\'t', '\g<1> not'),
(r'(\w+)\'ve', '\g<1> have'),
(r'(\w+t)\'s', '\g<1> is'),
(r'(\w+)\'re', '\g<1> are'),
(r'(\w+)\'d', '\g<1> would'),
]
class RegexpReplacer(object):
def __init__(self, patterns=replacement_patterns):
self.patterns = [(re.compile(regex), repl) for (regex, repl) in patterns]
def replace(self, line):
s = line
for (pattern, repl) in self.patterns:
(s, count) = re.subn(pattern, repl, s)
return s
完璧に動作しますが、txt ファイルでどのように使用できますか? 私は自分のやり方でやろうとしましたが、それは間違っていると思います
import nltk
f=open("C:/nltk_data/file.txt", "rU")
raw=f.readlines()
from replacers import RegexpReplacer
replacer=RegexpReplacer()
replacer.replace(raw)
事前にthx!!!