2016-10-28 5 views
0

私は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)) 

私はちょうど単語カウントとトークナイザを組み合わせなければなりませんでした。

+0

字下げは正しいですか? – cdarke

答えて

1

は、おそらく私が何かをしないのですが、あなたは、forループでラインを使用することはありません:

for line in f: 
    # Update the counter 
    count_all.update(terms_bigram) 

だから、各行で同じことをしている行をループしているだけです。

+0

Worked!ありがとうございました!元の質問を実際の解決策で編集します。 –

0

ファイルを読み込むために、これを試してみてください:このいけない作業は、ファイルのデータ形式についての詳細情報を投稿

with open(fname) as d: 
    tweet = json.load(d) 

場合。

新しいアップデート:

with open(fname) as d: 
    data = d.readlines() 

tweet = [json.loads(x) for x in data] 

これはあなたの辞書のリストが表示されます(JSON形式)

+0

エラーが発生しました - JSONDecodeError:Extra Data:2行目の1行目。ファイルデータフォーマットに関するオリジナルの投稿を編集します。ご協力いただきありがとうございます。 –

+0

新しいアップデートを確認する – Wonka

関連する問題