2016-10-28 4 views
0

저는 파이썬을 사용하여 일부 트윗을 처리하려고합니다. 그리고 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 개의 단어를 생성합니다.이 단어는 마지막 짹짹 (한 번) 만 읽었고 다른 짹짹은 읽지 않는다는 것을 의미합니다. 다음과 같이

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 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

관련 문제