Extracting Information from ~4.6 Million records of tweets, Problems with run-time on python












0















I have been trying to extract the urls from tweets and check the number of redirections, the meta content of the final url page the url redirects to.
[A tweet could contain multiple URLs]



I have ran the same in Python using pandas and splitting them into chunks, the code has been executing since over 9 days now. Any way you would suggest that this could be sped up?



for chunk in pd.read_csv('BotData.csv', chunksize=3000):
Bot_Data1 = chunk
pd.options.mode.chained_assignment = None # default='warn'
##get urls from tweet text
Bot_Data1['base_urls']=Bot_Data1['text'].apply(lambda
row:re.findall('https?://(?:[-w.]|(?:%[da-fA-F]{2}))+',str(row)))
Bot_Data1['urls']=Bot_Data1['text'].apply(lambda
row:re.findall('https?://(?:[-w.]|(?:%[da-fA-F]{2}))+[^
|^#|^https|^http]*',str(row)))

##get avg number of retweets for the number of URLs present
#clean urls
for i, value in enumerate(Bot_Data1['urls']):
Bot_Data1['urls'][i]= [s.replace('…', ' ') for s in value]
for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
numURL=0
i=0
finalurl=

for url in Bot_Data1['urls'][loop][:]:
numURL=numURL+1
i=i-1
f_url=''
# print(url)
try:
r = requests.get(url)
for h in r.history:
i=i+1
f_url=h.url
except Exception as e : # Catches wrong url error
print(e)

finalurl.append(f_url)
Bot_Data1['final_url'][loop]=np.array(finalurl,dtype=object)
if numURL!=0:
Bot_Data1['avg_redirections'][loop]=i/numURL
else:
Bot_Data1['avg_redirections'][loop]=0

for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
final_base_url=
for index, x in np.ndenumerate(Bot_Data1['final_url'][loop]):
final_base_url=final_base_url+(re.findall('https?://(?:[-w.]|(?:%
[da-fA-F]{2}))+',x))
Bot_Data1['final_base_url'][loop]=np.array(final_base_url,dtype=object)
##
##get url meta description content and title
import requests
import requests.exceptions

from bs4 import BeautifulSoup
Bot_Data1['url_meta_content']=''
for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
metacontent=''
for i in range(0,len(Bot_Data1['final_base_url'][loop])):
url=Bot_Data1['final_base_url'][loop][i]
# print(url)
try:
response = requests.get(url)
soup = BeautifulSoup(response.text)
metas = soup.find_all('meta')

title = soup.find('title')
metacontent+=" "
metacontent+=''.join(map(str, [meta.attrs['content']
for meta in metas if 'name' in meta.attrs and meta.attrs['name']
== 'description'])) #converting the meta content to string as
the output is a list
# print([ meta.attrs['content'] for meta in metas if 'name' in
meta.attrs and meta.attrs['name'] == 'description' ])
# print(title.string)
metacontent+=" "
try:
metacontent+=title.text.strip()

except AttributeError as error:
# Output expected AttributeErrors.
print(error)

except Exception as e:
print(e)
i=i-1

Bot_Data1['url_meta_content'][loop]=metacontent

Bot_Data1['url_meta_content']=Bot_Data1['url_meta_content'].replace("/n","")


concatChunk=[BOT_Data,Bot_Data1]
BOT_Data=pd.concat(concatChunk)
##









share|improve this question



























    0















    I have been trying to extract the urls from tweets and check the number of redirections, the meta content of the final url page the url redirects to.
    [A tweet could contain multiple URLs]



    I have ran the same in Python using pandas and splitting them into chunks, the code has been executing since over 9 days now. Any way you would suggest that this could be sped up?



    for chunk in pd.read_csv('BotData.csv', chunksize=3000):
    Bot_Data1 = chunk
    pd.options.mode.chained_assignment = None # default='warn'
    ##get urls from tweet text
    Bot_Data1['base_urls']=Bot_Data1['text'].apply(lambda
    row:re.findall('https?://(?:[-w.]|(?:%[da-fA-F]{2}))+',str(row)))
    Bot_Data1['urls']=Bot_Data1['text'].apply(lambda
    row:re.findall('https?://(?:[-w.]|(?:%[da-fA-F]{2}))+[^
    |^#|^https|^http]*',str(row)))

    ##get avg number of retweets for the number of URLs present
    #clean urls
    for i, value in enumerate(Bot_Data1['urls']):
    Bot_Data1['urls'][i]= [s.replace('…', ' ') for s in value]
    for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
    numURL=0
    i=0
    finalurl=

    for url in Bot_Data1['urls'][loop][:]:
    numURL=numURL+1
    i=i-1
    f_url=''
    # print(url)
    try:
    r = requests.get(url)
    for h in r.history:
    i=i+1
    f_url=h.url
    except Exception as e : # Catches wrong url error
    print(e)

    finalurl.append(f_url)
    Bot_Data1['final_url'][loop]=np.array(finalurl,dtype=object)
    if numURL!=0:
    Bot_Data1['avg_redirections'][loop]=i/numURL
    else:
    Bot_Data1['avg_redirections'][loop]=0

    for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
    final_base_url=
    for index, x in np.ndenumerate(Bot_Data1['final_url'][loop]):
    final_base_url=final_base_url+(re.findall('https?://(?:[-w.]|(?:%
    [da-fA-F]{2}))+',x))
    Bot_Data1['final_base_url'][loop]=np.array(final_base_url,dtype=object)
    ##
    ##get url meta description content and title
    import requests
    import requests.exceptions

    from bs4 import BeautifulSoup
    Bot_Data1['url_meta_content']=''
    for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
    metacontent=''
    for i in range(0,len(Bot_Data1['final_base_url'][loop])):
    url=Bot_Data1['final_base_url'][loop][i]
    # print(url)
    try:
    response = requests.get(url)
    soup = BeautifulSoup(response.text)
    metas = soup.find_all('meta')

    title = soup.find('title')
    metacontent+=" "
    metacontent+=''.join(map(str, [meta.attrs['content']
    for meta in metas if 'name' in meta.attrs and meta.attrs['name']
    == 'description'])) #converting the meta content to string as
    the output is a list
    # print([ meta.attrs['content'] for meta in metas if 'name' in
    meta.attrs and meta.attrs['name'] == 'description' ])
    # print(title.string)
    metacontent+=" "
    try:
    metacontent+=title.text.strip()

    except AttributeError as error:
    # Output expected AttributeErrors.
    print(error)

    except Exception as e:
    print(e)
    i=i-1

    Bot_Data1['url_meta_content'][loop]=metacontent

    Bot_Data1['url_meta_content']=Bot_Data1['url_meta_content'].replace("/n","")


    concatChunk=[BOT_Data,Bot_Data1]
    BOT_Data=pd.concat(concatChunk)
    ##









    share|improve this question

























      0












      0








      0








      I have been trying to extract the urls from tweets and check the number of redirections, the meta content of the final url page the url redirects to.
      [A tweet could contain multiple URLs]



      I have ran the same in Python using pandas and splitting them into chunks, the code has been executing since over 9 days now. Any way you would suggest that this could be sped up?



      for chunk in pd.read_csv('BotData.csv', chunksize=3000):
      Bot_Data1 = chunk
      pd.options.mode.chained_assignment = None # default='warn'
      ##get urls from tweet text
      Bot_Data1['base_urls']=Bot_Data1['text'].apply(lambda
      row:re.findall('https?://(?:[-w.]|(?:%[da-fA-F]{2}))+',str(row)))
      Bot_Data1['urls']=Bot_Data1['text'].apply(lambda
      row:re.findall('https?://(?:[-w.]|(?:%[da-fA-F]{2}))+[^
      |^#|^https|^http]*',str(row)))

      ##get avg number of retweets for the number of URLs present
      #clean urls
      for i, value in enumerate(Bot_Data1['urls']):
      Bot_Data1['urls'][i]= [s.replace('…', ' ') for s in value]
      for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
      numURL=0
      i=0
      finalurl=

      for url in Bot_Data1['urls'][loop][:]:
      numURL=numURL+1
      i=i-1
      f_url=''
      # print(url)
      try:
      r = requests.get(url)
      for h in r.history:
      i=i+1
      f_url=h.url
      except Exception as e : # Catches wrong url error
      print(e)

      finalurl.append(f_url)
      Bot_Data1['final_url'][loop]=np.array(finalurl,dtype=object)
      if numURL!=0:
      Bot_Data1['avg_redirections'][loop]=i/numURL
      else:
      Bot_Data1['avg_redirections'][loop]=0

      for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
      final_base_url=
      for index, x in np.ndenumerate(Bot_Data1['final_url'][loop]):
      final_base_url=final_base_url+(re.findall('https?://(?:[-w.]|(?:%
      [da-fA-F]{2}))+',x))
      Bot_Data1['final_base_url'][loop]=np.array(final_base_url,dtype=object)
      ##
      ##get url meta description content and title
      import requests
      import requests.exceptions

      from bs4 import BeautifulSoup
      Bot_Data1['url_meta_content']=''
      for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
      metacontent=''
      for i in range(0,len(Bot_Data1['final_base_url'][loop])):
      url=Bot_Data1['final_base_url'][loop][i]
      # print(url)
      try:
      response = requests.get(url)
      soup = BeautifulSoup(response.text)
      metas = soup.find_all('meta')

      title = soup.find('title')
      metacontent+=" "
      metacontent+=''.join(map(str, [meta.attrs['content']
      for meta in metas if 'name' in meta.attrs and meta.attrs['name']
      == 'description'])) #converting the meta content to string as
      the output is a list
      # print([ meta.attrs['content'] for meta in metas if 'name' in
      meta.attrs and meta.attrs['name'] == 'description' ])
      # print(title.string)
      metacontent+=" "
      try:
      metacontent+=title.text.strip()

      except AttributeError as error:
      # Output expected AttributeErrors.
      print(error)

      except Exception as e:
      print(e)
      i=i-1

      Bot_Data1['url_meta_content'][loop]=metacontent

      Bot_Data1['url_meta_content']=Bot_Data1['url_meta_content'].replace("/n","")


      concatChunk=[BOT_Data,Bot_Data1]
      BOT_Data=pd.concat(concatChunk)
      ##









      share|improve this question














      I have been trying to extract the urls from tweets and check the number of redirections, the meta content of the final url page the url redirects to.
      [A tweet could contain multiple URLs]



      I have ran the same in Python using pandas and splitting them into chunks, the code has been executing since over 9 days now. Any way you would suggest that this could be sped up?



      for chunk in pd.read_csv('BotData.csv', chunksize=3000):
      Bot_Data1 = chunk
      pd.options.mode.chained_assignment = None # default='warn'
      ##get urls from tweet text
      Bot_Data1['base_urls']=Bot_Data1['text'].apply(lambda
      row:re.findall('https?://(?:[-w.]|(?:%[da-fA-F]{2}))+',str(row)))
      Bot_Data1['urls']=Bot_Data1['text'].apply(lambda
      row:re.findall('https?://(?:[-w.]|(?:%[da-fA-F]{2}))+[^
      |^#|^https|^http]*',str(row)))

      ##get avg number of retweets for the number of URLs present
      #clean urls
      for i, value in enumerate(Bot_Data1['urls']):
      Bot_Data1['urls'][i]= [s.replace('…', ' ') for s in value]
      for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
      numURL=0
      i=0
      finalurl=

      for url in Bot_Data1['urls'][loop][:]:
      numURL=numURL+1
      i=i-1
      f_url=''
      # print(url)
      try:
      r = requests.get(url)
      for h in r.history:
      i=i+1
      f_url=h.url
      except Exception as e : # Catches wrong url error
      print(e)

      finalurl.append(f_url)
      Bot_Data1['final_url'][loop]=np.array(finalurl,dtype=object)
      if numURL!=0:
      Bot_Data1['avg_redirections'][loop]=i/numURL
      else:
      Bot_Data1['avg_redirections'][loop]=0

      for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
      final_base_url=
      for index, x in np.ndenumerate(Bot_Data1['final_url'][loop]):
      final_base_url=final_base_url+(re.findall('https?://(?:[-w.]|(?:%
      [da-fA-F]{2}))+',x))
      Bot_Data1['final_base_url'][loop]=np.array(final_base_url,dtype=object)
      ##
      ##get url meta description content and title
      import requests
      import requests.exceptions

      from bs4 import BeautifulSoup
      Bot_Data1['url_meta_content']=''
      for loop in range(min(Bot_Data1.index),max(Bot_Data1.index)):
      metacontent=''
      for i in range(0,len(Bot_Data1['final_base_url'][loop])):
      url=Bot_Data1['final_base_url'][loop][i]
      # print(url)
      try:
      response = requests.get(url)
      soup = BeautifulSoup(response.text)
      metas = soup.find_all('meta')

      title = soup.find('title')
      metacontent+=" "
      metacontent+=''.join(map(str, [meta.attrs['content']
      for meta in metas if 'name' in meta.attrs and meta.attrs['name']
      == 'description'])) #converting the meta content to string as
      the output is a list
      # print([ meta.attrs['content'] for meta in metas if 'name' in
      meta.attrs and meta.attrs['name'] == 'description' ])
      # print(title.string)
      metacontent+=" "
      try:
      metacontent+=title.text.strip()

      except AttributeError as error:
      # Output expected AttributeErrors.
      print(error)

      except Exception as e:
      print(e)
      i=i-1

      Bot_Data1['url_meta_content'][loop]=metacontent

      Bot_Data1['url_meta_content']=Bot_Data1['url_meta_content'].replace("/n","")


      concatChunk=[BOT_Data,Bot_Data1]
      BOT_Data=pd.concat(concatChunk)
      ##






      python pandas dataframe






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 27 '18 at 23:12









      aasthaaastha

      256




      256
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53509661%2fextracting-information-from-4-6-million-records-of-tweets-problems-with-run-ti%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53509661%2fextracting-information-from-4-6-million-records-of-tweets-problems-with-run-ti%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

          Calculate evaluation metrics using cross_val_predict sklearn

          Insert data from modal to MySQL (multiple modal on website)