0

大量の製品レビュー (20 万以上のレビュー) で使用されているすべての単語、2 単語、および 3 単語のフレーズのリストを取得しようとしています。レビューはjsonオブジェクトとして提供されます。ジェネレーターを使用してメモリからできるだけ多くのデータを削除しようとしましたが、まだメモリが不足しており、次にどこに行けばよいかわかりません。ここで、ジェネレーター/イテレーターの使用と非常によく似た問題を確認しました: Python のテキストで繰り返されるフレーズです が、大規模なデータセットに対してはまだ機能しません (レビューのサブセットを取得すると、私のコードはうまく機能します)。

私のコードの形式 (または少なくとも意図した形式) は次のとおりです。 -レビューを構成単語に分割し、単語を削除してマスター リストに追加するか、その単語/フレーズが既に存在する場合はそのカウンターをインクリメントします

どんな援助でも大歓迎です!

import json
import nltk
import collections

#define set of "stopwords", those that are removed
s_words=set(nltk.corpus.stopwords.words('english')).union(set(["it's", "us", " "]))

#load tokenizer, which will split text into words, and stemmer - which stems words
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
stemmer = nltk.SnowballStemmer('english')
master_wordlist = collections.defaultdict(int)
#open the raw data and read it in by line
allReviews = open('sample_reviews.json')
lines = allReviews.readlines()
allReviews.close()


#Get all of the words, 2 and 3 word phrases, in one review
def getAllWords(jsonObject):
    all_words = []
    phrase2 = []
    phrase3 = []

    sentences=tokenizer.tokenize(jsonObject['text'])
    for sentence in sentences:
        #split up the words and clean each word
        words = sentence.split()

        for word in words:
            adj_word = str(word).translate(None, '"""#$&*@.,!()-                     +?/[]1234567890\'').lower()
            #filter out stop words
            if adj_word not in s_words:

                all_words.append(str(stemmer.stem(adj_word)))

                #add all 2 word combos to list
                phrase2.append(str(word))
                if len(phrase2) > 2:
                    phrase2.remove(phrase2[0])
                if len(phrase2) == 2:
                    all_words.append(tuple(phrase2))

                #add all 3 word combos to list
                phrase3.append(str(word))
                if len(phrase3) > 3:
                    phrase3.remove(phrase3[0])
                if len(phrase3) == 3:
                    all_words.append(tuple(phrase3))

    return all_words
#end of getAllWords

#parse each line from the txt file to a json object
for c in lines:
    review = (json.loads(c))
    #counter instances of each unique word in wordlist
    for phrase in getAllWords(review):
        master_wordlist[phrase] += 1
4

1 に答える 1

1

呼び出すとreadlinesファイル全体がメモリにロードされると思います。ファイルオブジェクトを1行ずつ反復処理するためのオーバーヘッドが少なくなるはずです

#parse each line from the txt file to a json object
with open('sample_reviews.json') as f:
  for line in f:
    review = (json.loads(line))
    #counter instances of each unique word in wordlist
    for phrase in getAllWords(review):
        master_wordlist[phrase] += 1
于 2013-05-16T18:02:35.823 に答える