本文整理汇总了Python中nltk.corpus.util.LazyCorpusLoader.fileids方法的典型用法代码示例。如果您正苦于以下问题:Python LazyCorpusLoader.fileids方法的具体用法?Python LazyCorpusLoader.fileids怎么用?Python LazyCorpusLoader.fileids使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nltk.corpus.util.LazyCorpusLoader
的用法示例。
在下文中一共展示了LazyCorpusLoader.fileids方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: demo
# 需要导入模块: from nltk.corpus.util import LazyCorpusLoader [as 别名]
# 或者: from nltk.corpus.util.LazyCorpusLoader import fileids [as 别名]
def demo():
import nltk
from nltk.corpus.util import LazyCorpusLoader
root = nltk.data.find("corpora/knbc/corpus1")
fileids = [
f for f in find_corpus_fileids(FileSystemPathPointer(root), ".*") if re.search(r"\d\-\d\-[\d]+\-[\d]+", f)
]
def _knbc_fileids_sort(x):
cells = x.split("-")
return (cells[0], int(cells[1]), int(cells[2]), int(cells[3]))
knbc = LazyCorpusLoader("knbc/corpus1", KNBCorpusReader, sorted(fileids, key=_knbc_fileids_sort), encoding="euc-jp")
print knbc.fileids()[:10]
print "".join(knbc.words()[:100])
print "\n\n".join("%s" % tree for tree in knbc.parsed_sents()[:2])
knbc.morphs2str = lambda morphs: "/".join(
"%s(%s)" % (m[0], m[1].split(" ")[2]) for m in morphs if m[0] != "EOS"
).encode("utf-8")
print "\n\n".join("%s" % tree for tree in knbc.parsed_sents()[:2])
print "\n".join(" ".join("%s/%s" % (w[0], w[1].split(" ")[2]) for w in sent) for sent in knbc.tagged_sents()[0:2])
示例2: demo
# 需要导入模块: from nltk.corpus.util import LazyCorpusLoader [as 别名]
# 或者: from nltk.corpus.util.LazyCorpusLoader import fileids [as 别名]
def demo():
import nltk
from nltk.corpus.util import LazyCorpusLoader
root = nltk.data.find('corpora/knbc/corpus1')
fileids = [f for f in find_corpus_fileids(FileSystemPathPointer(root), ".*")
if re.search(r"\d\-\d\-[\d]+\-[\d]+", f)]
def _knbc_fileids_sort(x):
cells = x.split('-')
return (cells[0], int(cells[1]), int(cells[2]), int(cells[3]))
knbc = LazyCorpusLoader('knbc/corpus1', KNBCorpusReader,
sorted(fileids, key=_knbc_fileids_sort), encoding='euc-jp')
print knbc.fileids()[:10]
print ''.join( knbc.words()[:100] )
print '\n\n'.join( '%s' % tree for tree in knbc.parsed_sents()[:2] )
knbc.morphs2str = lambda morphs: '/'.join(
"%s(%s)"%(m[0], m[1].split(' ')[2]) for m in morphs if m[0] != 'EOS'
).encode('utf-8')
print '\n\n'.join( '%s' % tree for tree in knbc.parsed_sents()[:2] )
print '\n'.join( ' '.join("%s/%s"%(w[0], w[1].split(' ')[2]) for w in sent)
for sent in knbc.tagged_sents()[0:2] )
示例3: parse_wsj
# 需要导入模块: from nltk.corpus.util import LazyCorpusLoader [as 别名]
# 或者: from nltk.corpus.util.LazyCorpusLoader import fileids [as 别名]
def parse_wsj(processes=8):
ptb = LazyCorpusLoader( # Penn Treebank v3: WSJ portions
'ptb', CategorizedBracketParseCorpusReader, r'wsj/\d\d/wsj_\d\d\d\d.mrg',
cat_file='allcats.txt', tagset='wsj')
fileids = ptb.fileids()
params = []
for f in fileids:
corpus = zip(ptb.parsed_sents(f), ptb.tagged_sents(f))
for i, (parsed, tagged) in enumerate(corpus):
params.append((f, i, parsed, tagged))
p = Pool(processes)
p.starmap(get_best_parse, sorted(params, key=lambda x: (x[0], x[1])))
示例4: LazyCorpusLoader
# 需要导入模块: from nltk.corpus.util import LazyCorpusLoader [as 别名]
# 或者: from nltk.corpus.util.LazyCorpusLoader import fileids [as 别名]
wordlist = LazyCorpusLoader(
'bamana/wordlist', PlaintextCorpusReader, r'bailleul.clean.wordlist', word_tokenizer=orthographic_word, encoding='utf-8')
properlist = LazyCorpusLoader(
'bamana/propernames', PlaintextCorpusReader, r'.*\.clean\.wordlist', word_tokenizer=orthographic_word, encoding='utf-8')
propernames = LazyCorpusLoader(
'bamana/propernames', ToolboxCorpusReader, '.*\.txt', encoding='utf-8')
bailleul = LazyCorpusLoader(
'bamana/bailleul', ToolboxCorpusReader, r'bailleul.txt', encoding='utf-8')
lexicon = ElementTree(bailleul.xml('bailleul.txt'))
for file in propernames.fileids():
for e in ElementTree(propernames.xml(file)).findall('record'):
ge = Element('ge')
ge.text = e.find('lx').text
e.append(ge)
ps = Element('ps')
ps.text = 'n.prop'
e.append(ps)
lexicon.getroot().append(e)
wl = {}
wl_detone = {}
def normalize_bailleul(word):
return u''.join([c for c in word if c not in u'.-'])
示例5: loadClassifier
# 需要导入模块: from nltk.corpus.util import LazyCorpusLoader [as 别名]
# 或者: from nltk.corpus.util.LazyCorpusLoader import fileids [as 别名]
def loadClassifier(outputdir):
classifier_filename = os.path.join("pickled_algos", "voted_classifier.pickle")
word_features_filename = os.path.join("pickled_algos", "word_features.pickle")
if os.path.exists(classifier_filename) and os.path.exists(word_features_filename):
word_features = pickleLoad("word_features.pickle")
# classifier = pickleLoad("originalnaivebayes.pickle")
# MNB_classifier = pickleLoad("MNB_classifier.pickle")
# BernoulliNB_classifier = pickleLoad("BernoulliNB_classifier.pickle")
# LogisticRegression_classifier = pickleLoad("LogisticRegression_classifier.pickle")
# SGDClassifier_classifier = pickleLoad("SGDClassifier_classifier.pickle")
# LinearSVC_classifier = pickleLoad("LinearSVC_classifier.pickle")
#
# voted_classifier = VoteClassifier(classifier,
## NuSVC_classifier,
# LinearSVC_classifier,
# SGDClassifier_classifier,
# MNB_classifier,
# BernoulliNB_classifier,
# LogisticRegression_classifier)
voted_classifier= pickleLoad("voted_classifier.pickle")
return voted_classifier, word_features
else:
criticas_cine = LazyCorpusLoader(
'criticas_cine', CategorizedPlaintextCorpusReader,
r'(?!\.).*\.txt', cat_pattern=r'(neg|pos)/.*',
encoding='utf-8')
# criticas_cine = LazyCorpusLoader(
# 'criticas_cine_neu', CategorizedPlaintextCorpusReader,
# r'(?!\.).*\.txt', cat_pattern=r'(neg|neu|pos)/.*',
# encoding='utf-8')
documents = [(list(criticas_cine.words(fileid)), category)
for category in criticas_cine.categories()
for fileid in criticas_cine.fileids(category)]
#
# document_pos = [(list(criticas_cine.words(fileid)), "pos")
# for fileid in criticas_cine.fileids("pos")]
# document_neg = [(list(criticas_cine.words(fileid)), "neg")
# for fileid in criticas_cine.fileids("neg")]
# document_neu = [(list(criticas_cine.words(fileid)), "neu")
# for fileid in criticas_cine.fileids("neu")]
random.shuffle(documents)
# random.shuffle(document_pos)
# random.shuffle(document_neg)
# random.shuffle(document_neu)
all_words = []
for w in criticas_cine.words():
all_words.append(w.lower())
# for w in criticas_cine.words():
# if not is_filtered(w.lower()):
# all_words.append(w.lower())
#
all_words = nltk.FreqDist(all_words)
#print (all_words.most_common(50))
# Filtering by type of word
# for sample in all_words:
word_features = list(all_words.keys())[:3000]
pickleDump(word_features, "word_features.pickle")
featuresets = [(find_features(rev, word_features), category) for (rev, category) in documents]
# featuresetpos = [(find_features(rev, word_features), category) for (rev, category) in document_pos]
# featuresetneg = [(find_features(rev, word_features), category) for (rev, category) in document_neg]
# featuresetneu = [(find_features(rev, word_features), category) for (rev, category) in document_neu]
# training_set = featuresetpos[:1000]
# training_set.extend(featuresetneg[:1000])
# training_set.extend(featuresetneu[:1000])
# testing_set = featuresetpos[1000:1273]
# testing_set.extend(featuresetneg[1000:])
# testing_set.extend(featuresetneu[1000:])
# pos_feat = [(featuresSet, category) for (featuresSet, category) in featuresets if category == "pos"]
# neu_feat = [(featuresSet, category) for (featuresSet, category) in featuresets if category == "neu"]
# neg_feat = [(featuresSet, category) for (featuresSet, category) in featuresets if category == "neg"]
training_set = featuresets[:2000]
testing_set = featuresets[2000:]
classifier = nltk.NaiveBayesClassifier.train(training_set)
# pickleDump(classifier, "originalnaivebayes.pickle")
NaiveBayesClassifierAccuracy = nltk.classify.accuracy(classifier, testing_set)
print("Original Naive Bayes Algo accuracy percent:", (NaiveBayesClassifierAccuracy)*100)
accuracy = Accuracy(classifier,testing_set)
print(accuracy)
# order: neu, neg, pos
# print("Accuracy: ", (accuracy["neg"][0]+accuracy["pos"][2])/3)
# print("Discarded: ", (accuracy["neu"][0]+accuracy["neg"][1]+accuracy["pos"][0])/3)
#.........这里部分代码省略.........
示例6: LazyCorpusLoader
# 需要导入模块: from nltk.corpus.util import LazyCorpusLoader [as 别名]
# 或者: from nltk.corpus.util.LazyCorpusLoader import fileids [as 别名]
interrogazioni = LazyCorpusLoader(
'opp_interrogazioni_macro',
CategorizedPlaintextCorpusReader,
r'\d*', cat_file='cats.txt', cat_delimiter=','
)
print "computing FreqDist over all words"
all_words = nltk.FreqDist(w.lower() for w in interrogazioni.words())
top_words = all_words.keys()[:2000]
print "generating list of documents for each category"
documents = [
(list(interrogazioni.words(fileid)), category)
for category in interrogazioni.categories()
for fileid in interrogazioni.fileids(category)
]
random.shuffle(documents)
print "building the classifier"
featuresets = [(document_features(d, top_words), c) for (d,c) in documents]
train_set, test_set = featuresets[1000:], featuresets[:1000]
classifier = nltk.NaiveBayesClassifier.train(train_set)
print "classifier accuracy: ", nltk.classify.accuracy(classifier, test_set)
示例7: pickleObject
# 需要导入模块: from nltk.corpus.util import LazyCorpusLoader [as 别名]
# 或者: from nltk.corpus.util.LazyCorpusLoader import fileids [as 别名]
train_test_ratio = 2.0/3
def pickleObject():
obj = classifier
savefile = open('classifier.pickle', 'w')
cPickle.dump(obj, savefile, cPickle.HIGHEST_PROTOCOL)
def pickleFeats():
obj = words_in_sentence
savefile = open('feats.pickle', 'w')
cPickle.dump(obj, savefile, cPickle.HIGHEST_PROTOCOL)
files_in_neg = movie_reviews.fileids('neg')
files_in_pos = movie_reviews.fileids('pos')
neg_data = [(words_in_sentence(movie_reviews.words(fileids=[f])), 'neg') for f in files_in_neg]
pos_data = [(words_in_sentence(movie_reviews.words(fileids=[f])), 'pos') for f in files_in_pos]
negative_first_test_pos = int(len(neg_data)*train_test_ratio)
positive_first_test_pos = int(len(pos_data)*train_test_ratio)
train_data = neg_data[:negative_first_test_pos] + pos_data[:positive_first_test_pos]
test_data = neg_data[negative_first_test_pos:] + pos_data[positive_first_test_pos:]
print 'training on %d paragraphs and testing on %d paragraphs' % (len(train_data), len(test_data))
classifier = NaiveBayesClassifier.train(train_data)
print 'accuracy:', nltk.classify.util.accuracy(classifier, test_data)
classifier.show_most_informative_features(20)
示例8: LazyCorpusLoader
# 需要导入模块: from nltk.corpus.util import LazyCorpusLoader [as 别名]
# 或者: from nltk.corpus.util.LazyCorpusLoader import fileids [as 别名]
from nltk.corpus.util import LazyCorpusLoader
from nltk.corpus.reader import WordListCorpusReader
reader = LazyCorpusLoader('cookbook', WordListCorpusReader, ['wordlist.txt'])
print(isinstance(reader, LazyCorpusLoader))
print(reader.fileids())
print(isinstance(reader, LazyCorpusLoader))
print(isinstance(reader, WordListCorpusReader))
示例9: summarize_cisco_support_forum_texts
# 需要导入模块: from nltk.corpus.util import LazyCorpusLoader [as 别名]
# 或者: from nltk.corpus.util.LazyCorpusLoader import fileids [as 别名]
def summarize_cisco_support_forum_texts():
# cisco_plain_text = LazyCorpusLoader(
# 'content', PlaintextCorpusReader, r'(?!\.).*\.txt', encoding='latin_1')
cisco_plain_text = LazyCorpusLoader(
"cisco_forum_subset", PlaintextCorpusReader, r"(?!\.).*\.txt", encoding="latin_1"
)
token_dict = {}
for article in cisco_plain_text.fileids():
token_dict[article] = cisco_plain_text.raw(article)
tfidf = TfidfVectorizer(tokenizer=tokenize_and_stem, stop_words="english", decode_error="ignore")
sys.stdout.flush()
# creates Compressed Sparse Row format numpy matrix
tdm = tfidf.fit_transform(token_dict.values())
feature_names = tfidf.get_feature_names()
# problem_statement_#1 - summarize support_forum articles automatically
for article_id in range(0, tdm.shape[0] - 2):
article_text = cisco_plain_text.raw(cisco_plain_text.fileids()[article_id])
sent_scores = []
for sentence in nltk.sent_tokenize(article_text):
score = 0
sent_tokens = tokenize_and_stem(sentence)
for token in (t for t in sent_tokens if t in feature_names):
score += tdm[article_id, feature_names.index(token)]
sent_scores.append((score / len(sent_tokens), sentence))
summary_length = int(math.ceil(len(sent_scores) / 5))
sent_scores.sort(key=lambda sent: sent[0])
print "\n*** SUMMARY ***"
for summary_sentence in sent_scores[:summary_length]:
print summary_sentence[1]
print "\n*** ORIGINAL ***"
print article_text
# problem_statement_#2 - automatically categorize forum posts by tags into various groups
reduce_dimensionality_and_cluster_docs(tfidf, tdm, num_features=200)
# problem_statement_#3 - find similar documents to a current document (that user is reading) automatically
# eg - quora: find similar questions, find similar answers
cosine_similarity(tdm[0:1], tdm)
"""
output looks like this
array([[ 1. , 0.22185251, 0.0215558 , 0.03805012, 0.04796646,
0.05069365, 0.05507056, 0.03374501, 0.03643342, 0.05308392,
0.06002623, 0.0298806 , 0.04177088, 0.0844478 , 0.07951179,
0.02822186, 0.03036787, 0.11022385, 0.0535391 , 0.10009412,
0.07432719, 0.03753424, 0.06596462, 0.01256566, 0.02135591,
0.13931643, 0.03062681, 0.02595649, 0.04897851, 0.06276997,
0.03173952, 0.01822134, 0.04043555, 0.06629454, 0.05436211,
0.0549144 , 0.04400169, 0.05157118, 0.05409632, 0.09541703,
0.02473209, 0.05646599, 0.05728387, 0.04672681, 0.04519217,
0.04126276, 0.06289187, 0.03116767, 0.04828476, 0.04745193,
0.01404426, 0.04201325, 0.023492 , 0.07138136, 0.03778315,
0.03677206, 0.02553581]])
The first document is compared to the rest, with the most similar to it being itself with score of 1, next most similar to it is document with score 0.22185251
"""
cosine_similarities = linear_kernel(tdm[0:1], tdm).flatten()
# mapping back to document_name space
related_docs_indices = cosine_similarities.argsort()
"""
document_ids
array([23, 50, 31, 24, 2, 52, 40, 56, 27, 15, 11, 16, 26, 47, 30, 7, 8,
55, 21, 54, 3, 32, 45, 12, 51, 36, 44, 43, 49, 4, 48, 28, 5, 37,
9, 18, 38, 34, 35, 6, 41, 42, 10, 29, 46, 22, 33, 53, 20, 14, 13,
39, 19, 17, 25, 1, 0])
docs 0 and 1 are very similar which are the following posts (last 2 array elements above when sorted)
https://supportforums.cisco.com/discussion/11469881/aniserver-failed-run-lms-40
and
supportforums.cisco.com/discussion/11469606/eos-lms-31-support-quest
"""
cosine_similarities[related_docs_indices]
for key, value in token_dict.iteritems():
print key, value
# find the actual posts which are the most similar
tfidf.inverse_transform(tdm)[0]
tfidf.inverse_transform(tdm)[1]
示例10: Driver
# 需要导入模块: from nltk.corpus.util import LazyCorpusLoader [as 别名]
# 或者: from nltk.corpus.util.LazyCorpusLoader import fileids [as 别名]
return source
connection = pyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=E:\\farsnettest.mdb")
c = connection.cursor()
#c.execute("select number,example from shir")
corpus = LazyCorpusLoader('hamshahricorpus',XMLCorpusReader, r'(?!\.).*\.xml')
word=u'شیر'
targ = 0
c.execute("select * from shir")
for row in c:
print row
#out = codecs.open('d:\\shirham.txt','w','utf-8')
for file in corpus.fileids():
#
# #if num==1000: break
for doc in corpus.xml(file).getchildren():
#
cat=doc.getchildren()[3].text#
text=doc.getchildren()[5].text
newtext=correctPersianString(text)
allwords=text.split()
sents=newtext.split('.')
for sent in sents:
if word in sent.split():
targ+=1