私はPythonを使用していくつかのつぶやきを処理しようとしていますが、私は7つの異なるつぶやきに含まれている最も人気のある単語の単語カウントをしようとしています。私は、各つぶやきは独自のライン上のJSONオブジェクトである、私のファイルがセットアップされている、と私は次のように使用して、各つぶやきをプリントアウトしようとすると、それは完璧に動作します:Python - 特定の状況でファイルの最後の行だけを読む
with open(fname, 'r') as f:
for line in f:
tweet = json.loads(line) # load it as Python dict
print(json.dumps(tweet, indent=4))
しかし、私がやろうとしていたときに私の単語数に似た何か、それはファイルの最後の行を7回、またはファイルの最後の行だけを一度読み込みます。私は結果からストップワードを削除し、次のコードを使用しています:
with open(fname, 'r', encoding='utf8') as f:
count_all = Counter()
# Create a list with all the terms
terms_stop = [term for term in tokens if term not in stop]
for line in f:
# Update the counter
count_all.update(terms_stop)
# Print the first 5 most frequent words
print(count_all.most_common(5))
は、上記の最後のつぶやきから5つのランダム単語を生成し、それぞれのカウントは7である - それは、基本的に最後のつぶやきを読むことを意味7回の7つのつぶやきのそれぞれを読むのではなく、回。
次のコードは、どのワードが最も一般的にグループ化されているかを示しています。最後のつぶやきから無作為にグループ化された5つの単語を生成します。カウントは1だけで、最後のつぶやき(1回)と他のつぶやきは読み取られません。次のように
with open(fname, 'r', encoding='utf8') as f:
count_all = Counter()
# Create a list with all the terms
terms_stop = [term for term in tokens if term not in stop]
# Import Bigrams to group words together
terms_bigram = bigrams(terms_stop)
for line in f:
# Update the counter
count_all.update(terms_bigram)
# Print the first 5 most frequent words
print(count_all.most_common(5))
私のJSONファイルの形式は次のとおりです。
{"created_at":"Tue Oct 25 11:24:54 +0000 2016","id":4444444444,.....}
{"created_at":..... }
{etc}
ヘルプが最もいただければ幸いです!非常に前もってありがとう。
更新日: どのように私はそれを逃したのか分かりませんが、助けをいただきありがとうございます! forループに 'line'を含めるのを忘れてしまった。ここに作業コードがあります:
with open(fname, 'r', encoding='utf8') as f:
count_all = Counter()
for line in f:
tweet = json.loads(line)
tokens = preprocess(tweet['text'])
# Create a list with all the terms
terms_stop = [term for term in tokens if term not in stop]
# Update the counter
count_all.update(terms_stop)
# Print the first 5 most frequent words
print(count_all.most_common(5))
私はちょうど単語カウントとトークナイザを組み合わせなければなりませんでした。
字下げは正しいですか? – cdarke