30 KiB
30 KiB
In [5]:
import pandas as pd
from classes import Tweet
from database import connect as connect_db
db = connect_db()In [6]:
# load in all tweet texts
cursor = db.find({'account': '@Maersk'})
text_list = list()
for element in cursor:
try:
text_list.append(element['text'])
except:
print(f"failed getting {element['_id']}")
print(f'got {len(text_list)} tweets')[0;31m---------------------------------------------------------------------------[0m [0;31mKeyboardInterrupt[0m Traceback (most recent call last) Cell [0;32mIn[6], line 4[0m [1;32m 2[0m cursor [39m=[39m db[39m.[39mfind({[39m'[39m[39maccount[39m[39m'[39m: [39m'[39m[39m@Maersk[39m[39m'[39m}) [1;32m 3[0m text_list [39m=[39m [39mlist[39m() [0;32m----> 4[0m [39mfor[39;00m element [39min[39;00m cursor: [1;32m 5[0m [39mtry[39;00m: [1;32m 6[0m text_list[39m.[39mappend(element[[39m'[39m[39mtext[39m[39m'[39m]) File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/cursor.py:1248[0m, in [0;36mCursor.next[0;34m(self)[0m [1;32m 1246[0m [39mif[39;00m [39mself[39m[39m.[39m__empty: [1;32m 1247[0m [39mraise[39;00m [39mStopIteration[39;00m [0;32m-> 1248[0m [39mif[39;00m [39mlen[39m([39mself[39m[39m.[39m__data) [39mor[39;00m [39mself[39;49m[39m.[39;49m_refresh(): [1;32m 1249[0m [39mreturn[39;00m [39mself[39m[39m.[39m__data[39m.[39mpopleft() [1;32m 1250[0m [39melse[39;00m: File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/cursor.py:1188[0m, in [0;36mCursor._refresh[0;34m(self)[0m [1;32m 1173[0m [39m# Exhaust cursors don't send getMore messages.[39;00m [1;32m 1174[0m g [39m=[39m [39mself[39m[39m.[39m_getmore_class( [1;32m 1175[0m [39mself[39m[39m.[39m__dbname, [1;32m 1176[0m [39mself[39m[39m.[39m__collname, [0;32m (...)[0m [1;32m 1186[0m [39mself[39m[39m.[39m__comment, [1;32m 1187[0m ) [0;32m-> 1188[0m [39mself[39;49m[39m.[39;49m__send_message(g) [1;32m 1190[0m [39mreturn[39;00m [39mlen[39m([39mself[39m[39m.[39m__data) File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/cursor.py:1052[0m, in [0;36mCursor.__send_message[0;34m(self, operation)[0m [1;32m 1049[0m [39mraise[39;00m InvalidOperation([39m"[39m[39mexhaust cursors do not support auto encryption[39m[39m"[39m) [1;32m 1051[0m [39mtry[39;00m: [0;32m-> 1052[0m response [39m=[39m client[39m.[39;49m_run_operation( [1;32m 1053[0m operation, [39mself[39;49m[39m.[39;49m_unpack_response, address[39m=[39;49m[39mself[39;49m[39m.[39;49m__address [1;32m 1054[0m ) [1;32m 1055[0m [39mexcept[39;00m OperationFailure [39mas[39;00m exc: [1;32m 1056[0m [39mif[39;00m exc[39m.[39mcode [39min[39;00m _CURSOR_CLOSED_ERRORS [39mor[39;00m [39mself[39m[39m.[39m__exhaust: [1;32m 1057[0m [39m# Don't send killCursors because the cursor is already closed.[39;00m File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/_csot.py:105[0m, in [0;36mapply.<locals>.csot_wrapper[0;34m(self, *args, **kwargs)[0m [1;32m 103[0m [39mwith[39;00m _TimeoutContext(timeout): [1;32m 104[0m [39mreturn[39;00m func([39mself[39m, [39m*[39margs, [39m*[39m[39m*[39mkwargs) [0;32m--> 105[0m [39mreturn[39;00m func([39mself[39;49m, [39m*[39;49margs, [39m*[39;49m[39m*[39;49mkwargs) File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/mongo_client.py:1330[0m, in [0;36mMongoClient._run_operation[0;34m(self, operation, unpack_res, address)[0m [1;32m 1325[0m operation[39m.[39mreset() [39m# Reset op in case of retry.[39;00m [1;32m 1326[0m [39mreturn[39;00m server[39m.[39mrun_operation( [1;32m 1327[0m sock_info, operation, read_preference, [39mself[39m[39m.[39m_event_listeners, unpack_res [1;32m 1328[0m ) [0;32m-> 1330[0m [39mreturn[39;00m [39mself[39;49m[39m.[39;49m_retryable_read( [1;32m 1331[0m _cmd, [1;32m 1332[0m operation[39m.[39;49mread_preference, [1;32m 1333[0m operation[39m.[39;49msession, [1;32m 1334[0m address[39m=[39;49maddress, [1;32m 1335[0m retryable[39m=[39;49m[39misinstance[39;49m(operation, message[39m.[39;49m_Query), [1;32m 1336[0m ) File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/_csot.py:105[0m, in [0;36mapply.<locals>.csot_wrapper[0;34m(self, *args, **kwargs)[0m [1;32m 103[0m [39mwith[39;00m _TimeoutContext(timeout): [1;32m 104[0m [39mreturn[39;00m func([39mself[39m, [39m*[39margs, [39m*[39m[39m*[39mkwargs) [0;32m--> 105[0m [39mreturn[39;00m func([39mself[39;49m, [39m*[39;49margs, [39m*[39;49m[39m*[39;49mkwargs) File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/mongo_client.py:1448[0m, in [0;36mMongoClient._retryable_read[0;34m(self, func, read_pref, session, address, retryable)[0m [1;32m 1446[0m [39massert[39;00m last_error [39mis[39;00m [39mnot[39;00m [39mNone[39;00m [1;32m 1447[0m [39mraise[39;00m last_error [0;32m-> 1448[0m [39mreturn[39;00m func(session, server, sock_info, read_pref) [1;32m 1449[0m [39mexcept[39;00m ServerSelectionTimeoutError: [1;32m 1450[0m [39mif[39;00m retrying: [1;32m 1451[0m [39m# The application may think the write was never attempted[39;00m [1;32m 1452[0m [39m# if we raise ServerSelectionTimeoutError on the retry[39;00m [1;32m 1453[0m [39m# attempt. Raise the original exception instead.[39;00m File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/mongo_client.py:1326[0m, in [0;36mMongoClient._run_operation.<locals>._cmd[0;34m(session, server, sock_info, read_preference)[0m [1;32m 1324[0m [39mdef[39;00m [39m_cmd[39m(session, server, sock_info, read_preference): [1;32m 1325[0m operation[39m.[39mreset() [39m# Reset op in case of retry.[39;00m [0;32m-> 1326[0m [39mreturn[39;00m server[39m.[39;49mrun_operation( [1;32m 1327[0m sock_info, operation, read_preference, [39mself[39;49m[39m.[39;49m_event_listeners, unpack_res [1;32m 1328[0m ) File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/server.py:115[0m, in [0;36mServer.run_operation[0;34m(self, sock_info, operation, read_preference, listeners, unpack_res)[0m [1;32m 113[0m [39melse[39;00m: [1;32m 114[0m sock_info[39m.[39msend_message(data, max_doc_size) [0;32m--> 115[0m reply [39m=[39m sock_info[39m.[39;49mreceive_message(request_id) [1;32m 117[0m [39m# Unpack and check for command errors.[39;00m [1;32m 118[0m [39mif[39;00m use_cmd: File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/pool.py:821[0m, in [0;36mSocketInfo.receive_message[0;34m(self, request_id)[0m [1;32m 819[0m [39mreturn[39;00m receive_message([39mself[39m, request_id, [39mself[39m[39m.[39mmax_message_size) [1;32m 820[0m [39mexcept[39;00m [39mBaseException[39;00m [39mas[39;00m error: [0;32m--> 821[0m [39mself[39;49m[39m.[39;49m_raise_connection_failure(error) File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/pool.py:819[0m, in [0;36mSocketInfo.receive_message[0;34m(self, request_id)[0m [1;32m 814[0m [39m[39m[39m"""Receive a raw BSON message or raise ConnectionFailure.[39;00m [1;32m 815[0m [1;32m 816[0m [39mIf any exception is raised, the socket is closed.[39;00m [1;32m 817[0m [39m"""[39;00m [1;32m 818[0m [39mtry[39;00m: [0;32m--> 819[0m [39mreturn[39;00m receive_message([39mself[39;49m, request_id, [39mself[39;49m[39m.[39;49mmax_message_size) [1;32m 820[0m [39mexcept[39;00m [39mBaseException[39;00m [39mas[39;00m error: [1;32m 821[0m [39mself[39m[39m.[39m_raise_connection_failure(error) File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/network.py:238[0m, in [0;36mreceive_message[0;34m(sock_info, request_id, max_message_size)[0m [1;32m 236[0m data [39m=[39m decompress(_receive_data_on_socket(sock_info, length [39m-[39m [39m25[39m, deadline), compressor_id) [1;32m 237[0m [39melse[39;00m: [0;32m--> 238[0m data [39m=[39m _receive_data_on_socket(sock_info, length [39m-[39;49m [39m16[39;49m, deadline) [1;32m 240[0m [39mtry[39;00m: [1;32m 241[0m unpack_reply [39m=[39m _UNPACK_REPLY[op_code] File [0;32m~/Desktop/Solveig/venv/lib/python3.8/site-packages/pymongo/network.py:299[0m, in [0;36m_receive_data_on_socket[0;34m(sock_info, length, deadline)[0m [1;32m 297[0m [39mif[39;00m _csot[39m.[39mget_timeout(): [1;32m 298[0m sock_info[39m.[39mset_socket_timeout([39mmax[39m(deadline [39m-[39m time[39m.[39mmonotonic(), [39m0[39m)) [0;32m--> 299[0m chunk_length [39m=[39m sock_info[39m.[39;49msock[39m.[39;49mrecv_into(mv[bytes_read:]) [1;32m 300[0m [39mexcept[39;00m BLOCKING_IO_ERRORS: [1;32m 301[0m [39mraise[39;00m socket[39m.[39mtimeout([39m"[39m[39mtimed out[39m[39m"[39m) [0;31mKeyboardInterrupt[0m:
In [ ]:
Questions:
‘challengessee’
‘challengeor’
‘changetheworld’
‘changeat’
‘oceanswe’
‘planets’
‘futureproofing’
‘leadthefuture’
‘futureready’
‘futureproof’
'futureofshipping' # hashtag
In [48]:
for text in text_list:
if 'challengessee' in text:
print(text)In [20]:
# combine all text into one list
full_text = ' '.join(text_list)
full_text = full_text.replace('\n', ' ')
print('total characters: ', len(full_text))
full_text[:1000]Out [20]:
total characters: 906246
"A spotless deck before delivery Susan Mærsk was built by Odense Steel Shipyard in 1954 and a final inspection of the ship takes place before delivery. The ship was deployed on The Far East service - the company's first liner service initiated in 1928. #Maerskheritage #Maersk At #Maersk, we are honoured to partner with customers who share our vision for a cleaner, more sustainable future. By spearheading the movement to provide green shipping solutions, we’re building a brighter tomorrow for our world. More: https://bddy.me/3mSdkug #AllTheWay 14 years cooking for a multi-cultural crew! For Sandy, a workday onboard of Mette Maersk starts at 5:30 in the morning, as she gets ready to bake a new batch of fresh bread, to be ready in time for breakfast with great joy from the crew onboard. #Maersk #Lifeatsea #Chiefcook Embracing #Equity on #InternationalWomenDay! The transport and logistics industry has traditionally been male dominated, and this is no exception for Maersk. This needs to c"In [50]:
import re
len(re.findall('challengeor', full_text))Out [50]:
1
In [22]:
import re
len(re.findall(' CO2', full_text))Out [22]:
53
In [23]:
# clean text
from cleantext import clean
full_text = clean(
text=full_text,
fix_unicode=True,
to_ascii=True,
lower=True,
normalize_whitespace=True,
no_line_breaks=True,
no_urls=True,
no_emails=True,
no_phone_numbers=True,
no_numbers=True,
no_digits=False,
no_currency_symbols=True,
no_punct=True,
no_emoji=True,
replace_with_url='',
replace_with_email='',
replace_with_phone_number='',
replace_with_number='',
#replace_with_digit='', # to be able to handle CO2
replace_with_currency_symbol='',
replace_with_punct='',
lang='en'
)
# handle case from CO2 and remove other digits
#full_text = full_text.replace(' co<digit> ', ' co2 ')
#full_text = full_text.replace('<digit>', '')In [24]:
import re
re.findall('co[1-9]\w+', full_text)Out [24]:
['co2neutral', 'co2emission', 'co2emission', 'co1prbwlw', 'co1idd6st', 'co1l7bctb', 'co1lfltua', 'co1o1ksg7', 'co1ccchqp', 'co2emissions', 'co11bdxbv', 'co2neutral']
In [25]:
import re
re.findall(' CO2 ', full_text)Out [25]:
[]
In [26]:
import re
len(re.findall(' co2 ', full_text))Out [26]:
53
In [27]:
# remove unwanted word classes
import nltk
#nltk.download('punkt')
#nltk.download('averaged_perceptron_tagger')
token_list = nltk.word_tokenize(full_text)
tag_list = nltk.pos_tag(token_list)
unwanted_class_list = [
'CC', # coordinating conjunction
'DT', # determiner
'IN', # preposition/subordinating conjunction
'TO', # to go ‘to’ the store
'PRP', # personal pronoun I, he, she
'PRP$', # possessive pronoun my, his, hers
]
word_list = list()
for word, tag in tag_list:
if tag not in unwanted_class_list:
word_list.append(word)
print('total words: ', len(word_list))total words: 80155
In [28]:
# find unique words
unique_word_list = list(set(word_list))
print('total unique words: ', len(unique_word_list))total unique words: 10925
In [29]:
# count unique words
count_list = list()
for unique_word in unique_word_list:
count_list.append(word_list.count(unique_word))In [30]:
# present results
import pandas as pd
word_df = pd.DataFrame.from_dict(
{
'word': unique_word_list,
'counts': count_list
}
)
word_df = word_df.sort_values(by='counts', ascending=False).reset_index(drop=True)
word_df['ratio'] = word_df['counts'] / len(word_list)
word_df.head(30)Out [30]:
| word | counts | ratio | |
|---|---|---|---|
| 0 | maersk | 3207 | 0.040010 |
| 1 | is | 1025 | 0.012788 |
| 2 | more | 989 | 0.012339 |
| 3 | here | 825 | 0.010293 |
| 4 | trade | 642 | 0.008009 |
| 5 | are | 639 | 0.007972 |
| 6 | how | 634 | 0.007910 |
| 7 | logistics | 611 | 0.007623 |
| 8 | global | 467 | 0.005826 |
| 9 | new | 459 | 0.005726 |
| 10 | can | 453 | 0.005652 |
| 11 | shipping | 443 | 0.005527 |
| 12 | alltheway | 342 | 0.004267 |
| 13 | learn | 339 | 0.004229 |
| 14 | have | 314 | 0.003917 |
| 15 | be | 305 | 0.003805 |
| 16 | see | 302 | 0.003768 |
| 17 | supplychain | 296 | 0.003693 |
| 18 | supply | 295 | 0.003680 |
| 19 | will | 281 | 0.003506 |
| 20 | read | 274 | 0.003418 |
| 21 | has | 271 | 0.003381 |
| 22 | what | 267 | 0.003331 |
| 23 | world | 261 | 0.003256 |
| 24 | container | 248 | 0.003094 |
| 25 | business | 243 | 0.003032 |
| 26 | growth | 235 | 0.002932 |
| 27 | watch | 230 | 0.002869 |
| 28 | one | 228 | 0.002844 |
| 29 | up | 221 | 0.002757 |
In [31]:
# save results
word_df['ratio'] = word_df['ratio'].map('{:.5f}'.format) # ensure consistent formatting in csv
word_df.to_csv('word_count.csv')In [ ]: