Code is written to support multiple arguments, but fails when only one argument is given. sys.argv[1] +...












1















My current code uses a variable "word", so word = sys.argv[1] + sys.argv[2], which works great when I have two arguments, but when I only have one argument then i get IndexError: list index out of range



I am writing a program that Defines words by pulling the info from dictionary .com. I am following very closely a video tutorial because I am just trying to learn how to get a basic dictionary to work, (long term goal being write a translation app that is independent of google translate api or anything like that). I have a code that works in that it pulls the definition when you type in the word, but not when you type in 2 words, examples will be below. SO I added an argument, which worked for 2 words but no longer works for one word.



import requests
from bs4 import BeautifulSoup as bs
import sys

url = "https://www.dictionary.com/browse/"

word = sys.argv[1] + sys.argv[2]

url+= word
r = requests.get(url)
soup = bs(r.content, "lxml")


try:
pos = soup.findAll("span", {"class" : "luna-pos"})[0].text #luna-pos is an html tag
definitions = soup.findAll("ol")
meanings = definitions[0].findChildren("li", recursive=False)
print(word + ": " + pos)
for (i,meaning) in enumerate(meanings):
print(str(i + 1), meaning.text)
except:
print("Word not found")


Expected results:
Print word, part of speech, and definition.
I.e Define the word (being a single argument) "Proper"
Also Define "Self Control" (two word argument)










share|improve this question























  • just check how many args you have before trying to access the non existant [2] index? basic if condition.

    – Paritosh Singh
    Jan 1 at 19:47











  • @ParitoshSingh Not really the best solution. Then what will happen with 3 arguments? 4? 100?

    – DeepSpace
    Jan 1 at 19:49











  • aye thats true.

    – Paritosh Singh
    Jan 1 at 20:00
















1















My current code uses a variable "word", so word = sys.argv[1] + sys.argv[2], which works great when I have two arguments, but when I only have one argument then i get IndexError: list index out of range



I am writing a program that Defines words by pulling the info from dictionary .com. I am following very closely a video tutorial because I am just trying to learn how to get a basic dictionary to work, (long term goal being write a translation app that is independent of google translate api or anything like that). I have a code that works in that it pulls the definition when you type in the word, but not when you type in 2 words, examples will be below. SO I added an argument, which worked for 2 words but no longer works for one word.



import requests
from bs4 import BeautifulSoup as bs
import sys

url = "https://www.dictionary.com/browse/"

word = sys.argv[1] + sys.argv[2]

url+= word
r = requests.get(url)
soup = bs(r.content, "lxml")


try:
pos = soup.findAll("span", {"class" : "luna-pos"})[0].text #luna-pos is an html tag
definitions = soup.findAll("ol")
meanings = definitions[0].findChildren("li", recursive=False)
print(word + ": " + pos)
for (i,meaning) in enumerate(meanings):
print(str(i + 1), meaning.text)
except:
print("Word not found")


Expected results:
Print word, part of speech, and definition.
I.e Define the word (being a single argument) "Proper"
Also Define "Self Control" (two word argument)










share|improve this question























  • just check how many args you have before trying to access the non existant [2] index? basic if condition.

    – Paritosh Singh
    Jan 1 at 19:47











  • @ParitoshSingh Not really the best solution. Then what will happen with 3 arguments? 4? 100?

    – DeepSpace
    Jan 1 at 19:49











  • aye thats true.

    – Paritosh Singh
    Jan 1 at 20:00














1












1








1








My current code uses a variable "word", so word = sys.argv[1] + sys.argv[2], which works great when I have two arguments, but when I only have one argument then i get IndexError: list index out of range



I am writing a program that Defines words by pulling the info from dictionary .com. I am following very closely a video tutorial because I am just trying to learn how to get a basic dictionary to work, (long term goal being write a translation app that is independent of google translate api or anything like that). I have a code that works in that it pulls the definition when you type in the word, but not when you type in 2 words, examples will be below. SO I added an argument, which worked for 2 words but no longer works for one word.



import requests
from bs4 import BeautifulSoup as bs
import sys

url = "https://www.dictionary.com/browse/"

word = sys.argv[1] + sys.argv[2]

url+= word
r = requests.get(url)
soup = bs(r.content, "lxml")


try:
pos = soup.findAll("span", {"class" : "luna-pos"})[0].text #luna-pos is an html tag
definitions = soup.findAll("ol")
meanings = definitions[0].findChildren("li", recursive=False)
print(word + ": " + pos)
for (i,meaning) in enumerate(meanings):
print(str(i + 1), meaning.text)
except:
print("Word not found")


Expected results:
Print word, part of speech, and definition.
I.e Define the word (being a single argument) "Proper"
Also Define "Self Control" (two word argument)










share|improve this question














My current code uses a variable "word", so word = sys.argv[1] + sys.argv[2], which works great when I have two arguments, but when I only have one argument then i get IndexError: list index out of range



I am writing a program that Defines words by pulling the info from dictionary .com. I am following very closely a video tutorial because I am just trying to learn how to get a basic dictionary to work, (long term goal being write a translation app that is independent of google translate api or anything like that). I have a code that works in that it pulls the definition when you type in the word, but not when you type in 2 words, examples will be below. SO I added an argument, which worked for 2 words but no longer works for one word.



import requests
from bs4 import BeautifulSoup as bs
import sys

url = "https://www.dictionary.com/browse/"

word = sys.argv[1] + sys.argv[2]

url+= word
r = requests.get(url)
soup = bs(r.content, "lxml")


try:
pos = soup.findAll("span", {"class" : "luna-pos"})[0].text #luna-pos is an html tag
definitions = soup.findAll("ol")
meanings = definitions[0].findChildren("li", recursive=False)
print(word + ": " + pos)
for (i,meaning) in enumerate(meanings):
print(str(i + 1), meaning.text)
except:
print("Word not found")


Expected results:
Print word, part of speech, and definition.
I.e Define the word (being a single argument) "Proper"
Also Define "Self Control" (two word argument)







python web-scraping translators






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 1 at 19:44









Jadon MurphyJadon Murphy

295




295













  • just check how many args you have before trying to access the non existant [2] index? basic if condition.

    – Paritosh Singh
    Jan 1 at 19:47











  • @ParitoshSingh Not really the best solution. Then what will happen with 3 arguments? 4? 100?

    – DeepSpace
    Jan 1 at 19:49











  • aye thats true.

    – Paritosh Singh
    Jan 1 at 20:00



















  • just check how many args you have before trying to access the non existant [2] index? basic if condition.

    – Paritosh Singh
    Jan 1 at 19:47











  • @ParitoshSingh Not really the best solution. Then what will happen with 3 arguments? 4? 100?

    – DeepSpace
    Jan 1 at 19:49











  • aye thats true.

    – Paritosh Singh
    Jan 1 at 20:00

















just check how many args you have before trying to access the non existant [2] index? basic if condition.

– Paritosh Singh
Jan 1 at 19:47





just check how many args you have before trying to access the non existant [2] index? basic if condition.

– Paritosh Singh
Jan 1 at 19:47













@ParitoshSingh Not really the best solution. Then what will happen with 3 arguments? 4? 100?

– DeepSpace
Jan 1 at 19:49





@ParitoshSingh Not really the best solution. Then what will happen with 3 arguments? 4? 100?

– DeepSpace
Jan 1 at 19:49













aye thats true.

– Paritosh Singh
Jan 1 at 20:00





aye thats true.

– Paritosh Singh
Jan 1 at 20:00












2 Answers
2






active

oldest

votes


















3














This is a good use-case for slicing. You want everything after the first argument in the list, so as a slice this translates to [1:]. So just use:



word = ''.join(sys.argv[1:])


For example:



>>> args = ['scriptname.py', 'the']
>>> ''.join(args[1:])
'the'
>>> args = ['scriptname.py', 'self', 'control']
>>> ''.join(args[1:])
'selfcontrol'





share|improve this answer
























  • Hey thanks this seems to be working

    – Jadon Murphy
    Jan 1 at 19:50











  • @JadonMurphy Consider accepting the answer if it solved your problem.

    – Bitto Bennichan
    Jan 1 at 19:50






  • 1





    @bitto I will be it just says I have to wait some minutes. Thanks

    – Jadon Murphy
    Jan 1 at 19:58



















5














Slicing:



You can use list slicing to avoid the error:



word = ''.join(sys.argv[1:]  # joins 1st to last ..


or



word = ''.join(sys.argv[1:3]  # 1st and 2nd without error 


List slicing works even if the slice index is larger then the amount of elements in the list.





Testing:



The other way to handle it would be to test first then append:



if len(sys.argv) == 2:
word = sys.argv[1]
elif len(sys.argv) >= 3:
word = sys.argv[1]+sys.argv[2]
else:
word = "" # no input given




Error handling:



Try it and handle the error if it happens (see Ask forgiveness not permission below)



try:
word = sys.argv[1]+sys.argv[2]
except IndexError:
word = sys.argv[1]


Readup:




  • Understanding Python's slice notation

  • len() check

  • "Ask forgiveness not permission" - explain

  • try: except:






share|improve this answer

























    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%2f53998430%2fcode-is-written-to-support-multiple-arguments-but-fails-when-only-one-argument%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    This is a good use-case for slicing. You want everything after the first argument in the list, so as a slice this translates to [1:]. So just use:



    word = ''.join(sys.argv[1:])


    For example:



    >>> args = ['scriptname.py', 'the']
    >>> ''.join(args[1:])
    'the'
    >>> args = ['scriptname.py', 'self', 'control']
    >>> ''.join(args[1:])
    'selfcontrol'





    share|improve this answer
























    • Hey thanks this seems to be working

      – Jadon Murphy
      Jan 1 at 19:50











    • @JadonMurphy Consider accepting the answer if it solved your problem.

      – Bitto Bennichan
      Jan 1 at 19:50






    • 1





      @bitto I will be it just says I have to wait some minutes. Thanks

      – Jadon Murphy
      Jan 1 at 19:58
















    3














    This is a good use-case for slicing. You want everything after the first argument in the list, so as a slice this translates to [1:]. So just use:



    word = ''.join(sys.argv[1:])


    For example:



    >>> args = ['scriptname.py', 'the']
    >>> ''.join(args[1:])
    'the'
    >>> args = ['scriptname.py', 'self', 'control']
    >>> ''.join(args[1:])
    'selfcontrol'





    share|improve this answer
























    • Hey thanks this seems to be working

      – Jadon Murphy
      Jan 1 at 19:50











    • @JadonMurphy Consider accepting the answer if it solved your problem.

      – Bitto Bennichan
      Jan 1 at 19:50






    • 1





      @bitto I will be it just says I have to wait some minutes. Thanks

      – Jadon Murphy
      Jan 1 at 19:58














    3












    3








    3







    This is a good use-case for slicing. You want everything after the first argument in the list, so as a slice this translates to [1:]. So just use:



    word = ''.join(sys.argv[1:])


    For example:



    >>> args = ['scriptname.py', 'the']
    >>> ''.join(args[1:])
    'the'
    >>> args = ['scriptname.py', 'self', 'control']
    >>> ''.join(args[1:])
    'selfcontrol'





    share|improve this answer













    This is a good use-case for slicing. You want everything after the first argument in the list, so as a slice this translates to [1:]. So just use:



    word = ''.join(sys.argv[1:])


    For example:



    >>> args = ['scriptname.py', 'the']
    >>> ''.join(args[1:])
    'the'
    >>> args = ['scriptname.py', 'self', 'control']
    >>> ''.join(args[1:])
    'selfcontrol'






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jan 1 at 19:47









    juanpa.arrivillagajuanpa.arrivillaga

    38.8k33975




    38.8k33975













    • Hey thanks this seems to be working

      – Jadon Murphy
      Jan 1 at 19:50











    • @JadonMurphy Consider accepting the answer if it solved your problem.

      – Bitto Bennichan
      Jan 1 at 19:50






    • 1





      @bitto I will be it just says I have to wait some minutes. Thanks

      – Jadon Murphy
      Jan 1 at 19:58



















    • Hey thanks this seems to be working

      – Jadon Murphy
      Jan 1 at 19:50











    • @JadonMurphy Consider accepting the answer if it solved your problem.

      – Bitto Bennichan
      Jan 1 at 19:50






    • 1





      @bitto I will be it just says I have to wait some minutes. Thanks

      – Jadon Murphy
      Jan 1 at 19:58

















    Hey thanks this seems to be working

    – Jadon Murphy
    Jan 1 at 19:50





    Hey thanks this seems to be working

    – Jadon Murphy
    Jan 1 at 19:50













    @JadonMurphy Consider accepting the answer if it solved your problem.

    – Bitto Bennichan
    Jan 1 at 19:50





    @JadonMurphy Consider accepting the answer if it solved your problem.

    – Bitto Bennichan
    Jan 1 at 19:50




    1




    1





    @bitto I will be it just says I have to wait some minutes. Thanks

    – Jadon Murphy
    Jan 1 at 19:58





    @bitto I will be it just says I have to wait some minutes. Thanks

    – Jadon Murphy
    Jan 1 at 19:58













    5














    Slicing:



    You can use list slicing to avoid the error:



    word = ''.join(sys.argv[1:]  # joins 1st to last ..


    or



    word = ''.join(sys.argv[1:3]  # 1st and 2nd without error 


    List slicing works even if the slice index is larger then the amount of elements in the list.





    Testing:



    The other way to handle it would be to test first then append:



    if len(sys.argv) == 2:
    word = sys.argv[1]
    elif len(sys.argv) >= 3:
    word = sys.argv[1]+sys.argv[2]
    else:
    word = "" # no input given




    Error handling:



    Try it and handle the error if it happens (see Ask forgiveness not permission below)



    try:
    word = sys.argv[1]+sys.argv[2]
    except IndexError:
    word = sys.argv[1]


    Readup:




    • Understanding Python's slice notation

    • len() check

    • "Ask forgiveness not permission" - explain

    • try: except:






    share|improve this answer






























      5














      Slicing:



      You can use list slicing to avoid the error:



      word = ''.join(sys.argv[1:]  # joins 1st to last ..


      or



      word = ''.join(sys.argv[1:3]  # 1st and 2nd without error 


      List slicing works even if the slice index is larger then the amount of elements in the list.





      Testing:



      The other way to handle it would be to test first then append:



      if len(sys.argv) == 2:
      word = sys.argv[1]
      elif len(sys.argv) >= 3:
      word = sys.argv[1]+sys.argv[2]
      else:
      word = "" # no input given




      Error handling:



      Try it and handle the error if it happens (see Ask forgiveness not permission below)



      try:
      word = sys.argv[1]+sys.argv[2]
      except IndexError:
      word = sys.argv[1]


      Readup:




      • Understanding Python's slice notation

      • len() check

      • "Ask forgiveness not permission" - explain

      • try: except:






      share|improve this answer




























        5












        5








        5







        Slicing:



        You can use list slicing to avoid the error:



        word = ''.join(sys.argv[1:]  # joins 1st to last ..


        or



        word = ''.join(sys.argv[1:3]  # 1st and 2nd without error 


        List slicing works even if the slice index is larger then the amount of elements in the list.





        Testing:



        The other way to handle it would be to test first then append:



        if len(sys.argv) == 2:
        word = sys.argv[1]
        elif len(sys.argv) >= 3:
        word = sys.argv[1]+sys.argv[2]
        else:
        word = "" # no input given




        Error handling:



        Try it and handle the error if it happens (see Ask forgiveness not permission below)



        try:
        word = sys.argv[1]+sys.argv[2]
        except IndexError:
        word = sys.argv[1]


        Readup:




        • Understanding Python's slice notation

        • len() check

        • "Ask forgiveness not permission" - explain

        • try: except:






        share|improve this answer















        Slicing:



        You can use list slicing to avoid the error:



        word = ''.join(sys.argv[1:]  # joins 1st to last ..


        or



        word = ''.join(sys.argv[1:3]  # 1st and 2nd without error 


        List slicing works even if the slice index is larger then the amount of elements in the list.





        Testing:



        The other way to handle it would be to test first then append:



        if len(sys.argv) == 2:
        word = sys.argv[1]
        elif len(sys.argv) >= 3:
        word = sys.argv[1]+sys.argv[2]
        else:
        word = "" # no input given




        Error handling:



        Try it and handle the error if it happens (see Ask forgiveness not permission below)



        try:
        word = sys.argv[1]+sys.argv[2]
        except IndexError:
        word = sys.argv[1]


        Readup:




        • Understanding Python's slice notation

        • len() check

        • "Ask forgiveness not permission" - explain

        • try: except:







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 1 at 20:05

























        answered Jan 1 at 19:50









        Patrick ArtnerPatrick Artner

        25.3k62444




        25.3k62444






























            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%2f53998430%2fcode-is-written-to-support-multiple-arguments-but-fails-when-only-one-argument%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

            MongoDB - Not Authorized To Execute Command

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

            Npm cannot find a required file even through it is in the searched directory