Eliminate unnecessary looping while parsing cable modem status tableOOP design of code representing units of measurementParsing Wikipedia table with PythonParsing HTML table into Pandas DataFrameParsing scraped data from html tableParsing of text file to a table

What defenses are there against being summoned by the Gate spell?

What would happen to a modern skyscraper if it rains micro blackholes?

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

What are these boxed doors outside store fronts in New York?

Fully-Firstable Anagram Sets

Why is Minecraft giving an OpenGL error?

What is a clear way to write a bar that has an extra beat?

LWC SFDX source push error TypeError: LWC1009: decl.moveTo is not a function

How much of data wrangling is a data scientist's job?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Paid for article while in US on F-1 visa?

How do I deal with an unproductive colleague in a small company?

Replacing matching entries in one column of a file by another column from a different file

How does one intimidate enemies without having the capacity for violence?

Do infinite dimensional systems make sense?

Intersection point of 2 lines defined by 2 points each

Today is the Center

LaTeX: Why are digits allowed in environments, but forbidden in commands?

How is it possible to have an ability score that is less than 3?

Character reincarnated...as a snail

What does it mean to describe someone as a butt steak?

Why doesn't H₄O²⁺ exist?

Why are electrically insulating heatsinks so rare? Is it just cost?

How does quantile regression compare to logistic regression with the variable split at the quantile?



Eliminate unnecessary looping while parsing cable modem status table


OOP design of code representing units of measurementParsing Wikipedia table with PythonParsing HTML table into Pandas DataFrameParsing scraped data from html tableParsing of text file to a table






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0












$begingroup$


I am writing a Python script that will be used to generate line protocol for inserting metrics into an InfluxDB. I'm parsing the status page of my cable modem. That part works. I receive the data and can extract the table of information I need.



The HTML for the table looks like this (yes, it has the commented out lines)



The I have below works, but it feels inefficient. I feel like I have a lot of loops and these feel unnecessary. I'm not sure how to be more efficient though.



The only change between this and my real code is that I've moved the HTML to pastebin to cut down on the length of this post. That pastebin is here and the HTML is not written or editable by me. It's generated on the cable modem. Since you aren't able to see the results of my cable modem by running the code I use to extract it from the modem, I hope this is good enough.



from bs4 import BeautifulSoup
import requests

results_url = "https://pastebin.com/raw/bLZLFzy6"
content = requests.get(results_url).text

measurement = "modem"
hostname = "home-modem"


def strip_uom(data):
"""Strip Unit of Measurement

Some of our fields come with unit of measure. Rip that out and keep only
the value of the field.
"""
uom = ["dB", "Hz", "dBmV", "Ksym/sec"]
dataset = []
for d in data:
if d.split(" ")[-1] in uom:
dataset.append(d.split(" ")[0])
else:
dataset.append(d)
return dataset


soup = BeautifulSoup(content, 'html.parser')
dstable = soup.find('table', 'id': 'dsTable')

# Pull the headers from the downstream table
# We want to make these tag friendly, so make them lowercase and remove spaces
dstable_tags = [td.get_text().lower().replace(" ", "_") for td in dstable.tr.find_all('td')]

# Pull out the rest of the data for each row in the table; associate it with the correct tag; Strip UoM
downstream_data = []
for row in dstable.find_all('tr')[1:]:
column_values = [col.get_text() for col in row.find_all('td')]
downstream_data.append(dict(zip(dstable_tags, strip_uom(column_values))))

# Print line protocol lines for telegraf's inputs.exec plugin to handle
for data in downstream_data:
line_protocol_line = f"measurement,hostname=hostname"
fields = ",".join(["=".join(_) for _ in data.items()])
line_protocol_line = line_protocol_line + f" channel=data['channel'] fields"
print(line_protocol_line)


Finally, the output this script generates is this:



modem,hostname=home-modem channel=1 channel=1,lock_status=Locked,modulation=QAM 256,channel_id=121,frequency=585000000,power=5.6,snr=37.0,correctables=19430,uncorrectables=11263
modem,hostname=home-modem channel=2 channel=2,lock_status=Locked,modulation=QAM 256,channel_id=6,frequency=591000000,power=5.7,snr=37.0,correctables=19520,uncorrectables=9512
modem,hostname=home-modem channel=3 channel=3,lock_status=Locked,modulation=QAM 256,channel_id=7,frequency=597000000,power=5.7,snr=36.8,correctables=17439,uncorrectables=9736
modem,hostname=home-modem channel=4 channel=4,lock_status=Locked,modulation=QAM 256,channel_id=8,frequency=603000000,power=5.9,snr=37.0,correctables=12743,uncorrectables=11156
modem,hostname=home-modem channel=5 channel=5,lock_status=Locked,modulation=QAM 256,channel_id=122,frequency=609000000,power=2.6,snr=36.6,correctables=1852963,uncorrectables=18388
modem,hostname=home-modem channel=6 channel=6,lock_status=Locked,modulation=QAM 256,channel_id=10,frequency=615000000,power=2.6,snr=37.0,correctables=844991,uncorrectables=14615
modem,hostname=home-modem channel=7 channel=7,lock_status=Locked,modulation=QAM 256,channel_id=11,frequency=621000000,power=2.5,snr=37.6,correctables=281024,uncorrectables=13998
modem,hostname=home-modem channel=8 channel=8,lock_status=Locked,modulation=QAM 256,channel_id=12,frequency=627000000,power=2.5,snr=35.9,correctables=77942,uncorrectables=13695


I have loops and list comprehensions to get the tags, associate data with tags for each row, and to generate the line protocol lines. I have two additional comprehensions in those and a loop to see if I need to strip out an included unit of measure. Can I eliminate some of these to be more efficient?



I am running all of this code on Python 3.6.7.









share







New contributor




NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$


















    0












    $begingroup$


    I am writing a Python script that will be used to generate line protocol for inserting metrics into an InfluxDB. I'm parsing the status page of my cable modem. That part works. I receive the data and can extract the table of information I need.



    The HTML for the table looks like this (yes, it has the commented out lines)



    The I have below works, but it feels inefficient. I feel like I have a lot of loops and these feel unnecessary. I'm not sure how to be more efficient though.



    The only change between this and my real code is that I've moved the HTML to pastebin to cut down on the length of this post. That pastebin is here and the HTML is not written or editable by me. It's generated on the cable modem. Since you aren't able to see the results of my cable modem by running the code I use to extract it from the modem, I hope this is good enough.



    from bs4 import BeautifulSoup
    import requests

    results_url = "https://pastebin.com/raw/bLZLFzy6"
    content = requests.get(results_url).text

    measurement = "modem"
    hostname = "home-modem"


    def strip_uom(data):
    """Strip Unit of Measurement

    Some of our fields come with unit of measure. Rip that out and keep only
    the value of the field.
    """
    uom = ["dB", "Hz", "dBmV", "Ksym/sec"]
    dataset = []
    for d in data:
    if d.split(" ")[-1] in uom:
    dataset.append(d.split(" ")[0])
    else:
    dataset.append(d)
    return dataset


    soup = BeautifulSoup(content, 'html.parser')
    dstable = soup.find('table', 'id': 'dsTable')

    # Pull the headers from the downstream table
    # We want to make these tag friendly, so make them lowercase and remove spaces
    dstable_tags = [td.get_text().lower().replace(" ", "_") for td in dstable.tr.find_all('td')]

    # Pull out the rest of the data for each row in the table; associate it with the correct tag; Strip UoM
    downstream_data = []
    for row in dstable.find_all('tr')[1:]:
    column_values = [col.get_text() for col in row.find_all('td')]
    downstream_data.append(dict(zip(dstable_tags, strip_uom(column_values))))

    # Print line protocol lines for telegraf's inputs.exec plugin to handle
    for data in downstream_data:
    line_protocol_line = f"measurement,hostname=hostname"
    fields = ",".join(["=".join(_) for _ in data.items()])
    line_protocol_line = line_protocol_line + f" channel=data['channel'] fields"
    print(line_protocol_line)


    Finally, the output this script generates is this:



    modem,hostname=home-modem channel=1 channel=1,lock_status=Locked,modulation=QAM 256,channel_id=121,frequency=585000000,power=5.6,snr=37.0,correctables=19430,uncorrectables=11263
    modem,hostname=home-modem channel=2 channel=2,lock_status=Locked,modulation=QAM 256,channel_id=6,frequency=591000000,power=5.7,snr=37.0,correctables=19520,uncorrectables=9512
    modem,hostname=home-modem channel=3 channel=3,lock_status=Locked,modulation=QAM 256,channel_id=7,frequency=597000000,power=5.7,snr=36.8,correctables=17439,uncorrectables=9736
    modem,hostname=home-modem channel=4 channel=4,lock_status=Locked,modulation=QAM 256,channel_id=8,frequency=603000000,power=5.9,snr=37.0,correctables=12743,uncorrectables=11156
    modem,hostname=home-modem channel=5 channel=5,lock_status=Locked,modulation=QAM 256,channel_id=122,frequency=609000000,power=2.6,snr=36.6,correctables=1852963,uncorrectables=18388
    modem,hostname=home-modem channel=6 channel=6,lock_status=Locked,modulation=QAM 256,channel_id=10,frequency=615000000,power=2.6,snr=37.0,correctables=844991,uncorrectables=14615
    modem,hostname=home-modem channel=7 channel=7,lock_status=Locked,modulation=QAM 256,channel_id=11,frequency=621000000,power=2.5,snr=37.6,correctables=281024,uncorrectables=13998
    modem,hostname=home-modem channel=8 channel=8,lock_status=Locked,modulation=QAM 256,channel_id=12,frequency=627000000,power=2.5,snr=35.9,correctables=77942,uncorrectables=13695


    I have loops and list comprehensions to get the tags, associate data with tags for each row, and to generate the line protocol lines. I have two additional comprehensions in those and a loop to see if I need to strip out an included unit of measure. Can I eliminate some of these to be more efficient?



    I am running all of this code on Python 3.6.7.









    share







    New contributor




    NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$














      0












      0








      0





      $begingroup$


      I am writing a Python script that will be used to generate line protocol for inserting metrics into an InfluxDB. I'm parsing the status page of my cable modem. That part works. I receive the data and can extract the table of information I need.



      The HTML for the table looks like this (yes, it has the commented out lines)



      The I have below works, but it feels inefficient. I feel like I have a lot of loops and these feel unnecessary. I'm not sure how to be more efficient though.



      The only change between this and my real code is that I've moved the HTML to pastebin to cut down on the length of this post. That pastebin is here and the HTML is not written or editable by me. It's generated on the cable modem. Since you aren't able to see the results of my cable modem by running the code I use to extract it from the modem, I hope this is good enough.



      from bs4 import BeautifulSoup
      import requests

      results_url = "https://pastebin.com/raw/bLZLFzy6"
      content = requests.get(results_url).text

      measurement = "modem"
      hostname = "home-modem"


      def strip_uom(data):
      """Strip Unit of Measurement

      Some of our fields come with unit of measure. Rip that out and keep only
      the value of the field.
      """
      uom = ["dB", "Hz", "dBmV", "Ksym/sec"]
      dataset = []
      for d in data:
      if d.split(" ")[-1] in uom:
      dataset.append(d.split(" ")[0])
      else:
      dataset.append(d)
      return dataset


      soup = BeautifulSoup(content, 'html.parser')
      dstable = soup.find('table', 'id': 'dsTable')

      # Pull the headers from the downstream table
      # We want to make these tag friendly, so make them lowercase and remove spaces
      dstable_tags = [td.get_text().lower().replace(" ", "_") for td in dstable.tr.find_all('td')]

      # Pull out the rest of the data for each row in the table; associate it with the correct tag; Strip UoM
      downstream_data = []
      for row in dstable.find_all('tr')[1:]:
      column_values = [col.get_text() for col in row.find_all('td')]
      downstream_data.append(dict(zip(dstable_tags, strip_uom(column_values))))

      # Print line protocol lines for telegraf's inputs.exec plugin to handle
      for data in downstream_data:
      line_protocol_line = f"measurement,hostname=hostname"
      fields = ",".join(["=".join(_) for _ in data.items()])
      line_protocol_line = line_protocol_line + f" channel=data['channel'] fields"
      print(line_protocol_line)


      Finally, the output this script generates is this:



      modem,hostname=home-modem channel=1 channel=1,lock_status=Locked,modulation=QAM 256,channel_id=121,frequency=585000000,power=5.6,snr=37.0,correctables=19430,uncorrectables=11263
      modem,hostname=home-modem channel=2 channel=2,lock_status=Locked,modulation=QAM 256,channel_id=6,frequency=591000000,power=5.7,snr=37.0,correctables=19520,uncorrectables=9512
      modem,hostname=home-modem channel=3 channel=3,lock_status=Locked,modulation=QAM 256,channel_id=7,frequency=597000000,power=5.7,snr=36.8,correctables=17439,uncorrectables=9736
      modem,hostname=home-modem channel=4 channel=4,lock_status=Locked,modulation=QAM 256,channel_id=8,frequency=603000000,power=5.9,snr=37.0,correctables=12743,uncorrectables=11156
      modem,hostname=home-modem channel=5 channel=5,lock_status=Locked,modulation=QAM 256,channel_id=122,frequency=609000000,power=2.6,snr=36.6,correctables=1852963,uncorrectables=18388
      modem,hostname=home-modem channel=6 channel=6,lock_status=Locked,modulation=QAM 256,channel_id=10,frequency=615000000,power=2.6,snr=37.0,correctables=844991,uncorrectables=14615
      modem,hostname=home-modem channel=7 channel=7,lock_status=Locked,modulation=QAM 256,channel_id=11,frequency=621000000,power=2.5,snr=37.6,correctables=281024,uncorrectables=13998
      modem,hostname=home-modem channel=8 channel=8,lock_status=Locked,modulation=QAM 256,channel_id=12,frequency=627000000,power=2.5,snr=35.9,correctables=77942,uncorrectables=13695


      I have loops and list comprehensions to get the tags, associate data with tags for each row, and to generate the line protocol lines. I have two additional comprehensions in those and a loop to see if I need to strip out an included unit of measure. Can I eliminate some of these to be more efficient?



      I am running all of this code on Python 3.6.7.









      share







      New contributor




      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I am writing a Python script that will be used to generate line protocol for inserting metrics into an InfluxDB. I'm parsing the status page of my cable modem. That part works. I receive the data and can extract the table of information I need.



      The HTML for the table looks like this (yes, it has the commented out lines)



      The I have below works, but it feels inefficient. I feel like I have a lot of loops and these feel unnecessary. I'm not sure how to be more efficient though.



      The only change between this and my real code is that I've moved the HTML to pastebin to cut down on the length of this post. That pastebin is here and the HTML is not written or editable by me. It's generated on the cable modem. Since you aren't able to see the results of my cable modem by running the code I use to extract it from the modem, I hope this is good enough.



      from bs4 import BeautifulSoup
      import requests

      results_url = "https://pastebin.com/raw/bLZLFzy6"
      content = requests.get(results_url).text

      measurement = "modem"
      hostname = "home-modem"


      def strip_uom(data):
      """Strip Unit of Measurement

      Some of our fields come with unit of measure. Rip that out and keep only
      the value of the field.
      """
      uom = ["dB", "Hz", "dBmV", "Ksym/sec"]
      dataset = []
      for d in data:
      if d.split(" ")[-1] in uom:
      dataset.append(d.split(" ")[0])
      else:
      dataset.append(d)
      return dataset


      soup = BeautifulSoup(content, 'html.parser')
      dstable = soup.find('table', 'id': 'dsTable')

      # Pull the headers from the downstream table
      # We want to make these tag friendly, so make them lowercase and remove spaces
      dstable_tags = [td.get_text().lower().replace(" ", "_") for td in dstable.tr.find_all('td')]

      # Pull out the rest of the data for each row in the table; associate it with the correct tag; Strip UoM
      downstream_data = []
      for row in dstable.find_all('tr')[1:]:
      column_values = [col.get_text() for col in row.find_all('td')]
      downstream_data.append(dict(zip(dstable_tags, strip_uom(column_values))))

      # Print line protocol lines for telegraf's inputs.exec plugin to handle
      for data in downstream_data:
      line_protocol_line = f"measurement,hostname=hostname"
      fields = ",".join(["=".join(_) for _ in data.items()])
      line_protocol_line = line_protocol_line + f" channel=data['channel'] fields"
      print(line_protocol_line)


      Finally, the output this script generates is this:



      modem,hostname=home-modem channel=1 channel=1,lock_status=Locked,modulation=QAM 256,channel_id=121,frequency=585000000,power=5.6,snr=37.0,correctables=19430,uncorrectables=11263
      modem,hostname=home-modem channel=2 channel=2,lock_status=Locked,modulation=QAM 256,channel_id=6,frequency=591000000,power=5.7,snr=37.0,correctables=19520,uncorrectables=9512
      modem,hostname=home-modem channel=3 channel=3,lock_status=Locked,modulation=QAM 256,channel_id=7,frequency=597000000,power=5.7,snr=36.8,correctables=17439,uncorrectables=9736
      modem,hostname=home-modem channel=4 channel=4,lock_status=Locked,modulation=QAM 256,channel_id=8,frequency=603000000,power=5.9,snr=37.0,correctables=12743,uncorrectables=11156
      modem,hostname=home-modem channel=5 channel=5,lock_status=Locked,modulation=QAM 256,channel_id=122,frequency=609000000,power=2.6,snr=36.6,correctables=1852963,uncorrectables=18388
      modem,hostname=home-modem channel=6 channel=6,lock_status=Locked,modulation=QAM 256,channel_id=10,frequency=615000000,power=2.6,snr=37.0,correctables=844991,uncorrectables=14615
      modem,hostname=home-modem channel=7 channel=7,lock_status=Locked,modulation=QAM 256,channel_id=11,frequency=621000000,power=2.5,snr=37.6,correctables=281024,uncorrectables=13998
      modem,hostname=home-modem channel=8 channel=8,lock_status=Locked,modulation=QAM 256,channel_id=12,frequency=627000000,power=2.5,snr=35.9,correctables=77942,uncorrectables=13695


      I have loops and list comprehensions to get the tags, associate data with tags for each row, and to generate the line protocol lines. I have two additional comprehensions in those and a loop to see if I need to strip out an included unit of measure. Can I eliminate some of these to be more efficient?



      I am running all of this code on Python 3.6.7.







      python python-3.x beautifulsoup





      share







      New contributor




      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share







      New contributor




      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share



      share






      New contributor




      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 4 mins ago









      NewGuyNewGuy

      1011




      1011




      New contributor




      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















          0






          active

          oldest

          votes












          Your Answer





          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          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: "196"
          ;
          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: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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
          );



          );






          NewGuy is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216962%2feliminate-unnecessary-looping-while-parsing-cable-modem-status-table%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








          NewGuy is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          NewGuy is a new contributor. Be nice, and check out our Code of Conduct.












          NewGuy is a new contributor. Be nice, and check out our Code of Conduct.











          NewGuy is a new contributor. Be nice, and check out our Code of Conduct.














          Thanks for contributing an answer to Code Review Stack Exchange!


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

          Use MathJax to format equations. MathJax reference.


          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%2fcodereview.stackexchange.com%2fquestions%2f216962%2feliminate-unnecessary-looping-while-parsing-cable-modem-status-table%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

          कुँवर स्रोत दिक्चालन सूची"कुँवर""राणा कुँवरके वंशावली"

          Why is a white electrical wire connected to 2 black wires?How to wire a light fixture with 3 white wires in box?How should I wire a ceiling fan when there's only three wires in the box?Two white, two black, two ground, and red wire in ceiling box connected to switchWhy is there a white wire connected to multiple black wires in my light box?How to wire a light with two white wires and one black wireReplace light switch connected to a power outlet with dimmer - two black wires to one black and redHow to wire a light with multiple black/white/green wires from the ceiling?Ceiling box has 2 black and white wires but fan/ light only has 1 of eachWhy neutral wire connected to load wire?Switch with 2 black, 2 white, 2 ground and 1 red wire connected to ceiling light and a receptacle?

          चैत्य भूमि चित्र दीर्घा सन्दर्भ बाहरी कडियाँ दिक्चालन सूची"Chaitya Bhoomi""Chaitya Bhoomi: Statue of Equality in India""Dadar Chaitya Bhoomi: Statue of Equality in India""Ambedkar memorial: Centre okays transfer of Indu Mill land"चैत्यभमि