我是 Python NLTK 的新手,真的需要你的建议。我想打开我自己的 txt 文件并做一些预处理,比如用它的正则表达式替换单词。我已经尝试像在 NLTK 2.0 Cookbook 中那样做
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)
提前谢谢!!!