Simplifying many if-statements The Next CEO of Stack OverflowReplacements for switch statement in Python?Styling multi-line conditions in 'if' statements?Python's equivalent of && (logical-and) in an if-statementPutting a simple if-then-else statement on one lineHow do I compare two string variables in an 'if' statement in Bash?How to write inline if statement for print?if else statement in AngularJS templatesToo many 'if' statements?Simplifying an if statementsimplify if statement in python 3.6

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

Is it ever safe to open a suspicious HTML file (e.g. email attachment)?

Help/tips for a first time writer?

Film where the government was corrupt with aliens, people sent to kill aliens are given rigged visors not showing the right aliens

"Eavesdropping" vs "Listen in on"

Expressing the idea of having a very busy time

What does "shotgun unity" refer to here in this sentence?

Graph of the history of databases

Expectation in a stochastic differential equation

Traduction de « Life is a roller coaster »

Physiological effects of huge anime eyes

Can I board the first leg of the flight without having final country's visa?

Is there an equivalent of cd - for cp or mv

TikZ: How to fill area with a special pattern?

Does higher Oxidation/ reduction potential translate to higher energy storage in battery?

Is there such a thing as a proper verb, like a proper noun?

Can Sneak Attack be used when hitting with an improvised weapon?

Pulling the principal components out of a DimensionReducerFunction?

what's the use of '% to gdp' type of variables?

Why the last AS PATH item always is `I` or `?`?

Is it professional to write unrelated content in an almost-empty email?

Is it correct to say moon starry nights?

How did Beeri the Hittite come up with naming his daughter Yehudit?

What connection does MS Office have to Netscape Navigator?



Simplifying many if-statements



The Next CEO of Stack OverflowReplacements for switch statement in Python?Styling multi-line conditions in 'if' statements?Python's equivalent of && (logical-and) in an if-statementPutting a simple if-then-else statement on one lineHow do I compare two string variables in an 'if' statement in Bash?How to write inline if statement for print?if else statement in AngularJS templatesToo many 'if' statements?Simplifying an if statementsimplify if statement in python 3.6










0















Is there a way to simplify this pile of if-statements? This parsing function sure works (with the right dictionaries), but it has to test 6 if-statements for each word in the input. For a 5-word sentence that would be 30 if-statements. It is also kind of hard to read.



def parse(text):
predicate=False
directObjectAdjective=False
directObject=False
preposition=False
indirectObjectAdjective=False
indirectObject=False
text=text.casefold()
text=text.split()
for word in text:
if not predicate:
if word in predicateDict:
predicate=predicateDict[word]
continue
if not directObjectAdjective:
if word in adjectiveDict:
directObjectAdjective=adjectiveDict[word]
continue
if not directObject:
if word in objectDict:
directObject=objectDict[word]
continue
if not preposition:
if word in prepositionDict:
preposition=prepositionDict[word]
continue
if not indirectObjectAdjective:
if word in adjectiveDict:
indirectObjectAdjective=adjectiveDict[word]
continue
if not indirectObject:
if word in objectDict:
indirectObject=objectDict[word]
continue
if not directObject and directObjectAdjective:
directObject=directObjectAdjective
directObjectAdjective=False
if not indirectObject and indirectObjectAdjective:
indirectObject=indirectObjectAdjective
indirectObjectAdjective=False
return [predicate,directObjectAdjective,directObject,preposition,indirectObjectAdjective,indirectObject]


Here's also a sample of a dictionary, if that's needed.



predicateDict=
"grab":"take",
"pick":"take",
"collect":"take",
"acquire":"take",
"snag":"take",
"gather":"take",
"attain":"take",
"capture":"take",
"take":"take"









share|improve this question






















  • Does a switch statement work for your use case? jaxenter.com/implement-switch-case-statement-python-138315.html

    – Sam
    Mar 7 at 17:39











  • This pattern "if not something: if not word in someDict: something = someDict[word]" could be turned into a function.

    – Haroldo_OK
    Mar 7 at 17:43











  • From the performance side if you want only if to be executed then use elif rather than series of if

    – mad_
    Mar 7 at 17:48















0















Is there a way to simplify this pile of if-statements? This parsing function sure works (with the right dictionaries), but it has to test 6 if-statements for each word in the input. For a 5-word sentence that would be 30 if-statements. It is also kind of hard to read.



def parse(text):
predicate=False
directObjectAdjective=False
directObject=False
preposition=False
indirectObjectAdjective=False
indirectObject=False
text=text.casefold()
text=text.split()
for word in text:
if not predicate:
if word in predicateDict:
predicate=predicateDict[word]
continue
if not directObjectAdjective:
if word in adjectiveDict:
directObjectAdjective=adjectiveDict[word]
continue
if not directObject:
if word in objectDict:
directObject=objectDict[word]
continue
if not preposition:
if word in prepositionDict:
preposition=prepositionDict[word]
continue
if not indirectObjectAdjective:
if word in adjectiveDict:
indirectObjectAdjective=adjectiveDict[word]
continue
if not indirectObject:
if word in objectDict:
indirectObject=objectDict[word]
continue
if not directObject and directObjectAdjective:
directObject=directObjectAdjective
directObjectAdjective=False
if not indirectObject and indirectObjectAdjective:
indirectObject=indirectObjectAdjective
indirectObjectAdjective=False
return [predicate,directObjectAdjective,directObject,preposition,indirectObjectAdjective,indirectObject]


Here's also a sample of a dictionary, if that's needed.



predicateDict=
"grab":"take",
"pick":"take",
"collect":"take",
"acquire":"take",
"snag":"take",
"gather":"take",
"attain":"take",
"capture":"take",
"take":"take"









share|improve this question






















  • Does a switch statement work for your use case? jaxenter.com/implement-switch-case-statement-python-138315.html

    – Sam
    Mar 7 at 17:39











  • This pattern "if not something: if not word in someDict: something = someDict[word]" could be turned into a function.

    – Haroldo_OK
    Mar 7 at 17:43











  • From the performance side if you want only if to be executed then use elif rather than series of if

    – mad_
    Mar 7 at 17:48













0












0








0








Is there a way to simplify this pile of if-statements? This parsing function sure works (with the right dictionaries), but it has to test 6 if-statements for each word in the input. For a 5-word sentence that would be 30 if-statements. It is also kind of hard to read.



def parse(text):
predicate=False
directObjectAdjective=False
directObject=False
preposition=False
indirectObjectAdjective=False
indirectObject=False
text=text.casefold()
text=text.split()
for word in text:
if not predicate:
if word in predicateDict:
predicate=predicateDict[word]
continue
if not directObjectAdjective:
if word in adjectiveDict:
directObjectAdjective=adjectiveDict[word]
continue
if not directObject:
if word in objectDict:
directObject=objectDict[word]
continue
if not preposition:
if word in prepositionDict:
preposition=prepositionDict[word]
continue
if not indirectObjectAdjective:
if word in adjectiveDict:
indirectObjectAdjective=adjectiveDict[word]
continue
if not indirectObject:
if word in objectDict:
indirectObject=objectDict[word]
continue
if not directObject and directObjectAdjective:
directObject=directObjectAdjective
directObjectAdjective=False
if not indirectObject and indirectObjectAdjective:
indirectObject=indirectObjectAdjective
indirectObjectAdjective=False
return [predicate,directObjectAdjective,directObject,preposition,indirectObjectAdjective,indirectObject]


Here's also a sample of a dictionary, if that's needed.



predicateDict=
"grab":"take",
"pick":"take",
"collect":"take",
"acquire":"take",
"snag":"take",
"gather":"take",
"attain":"take",
"capture":"take",
"take":"take"









share|improve this question














Is there a way to simplify this pile of if-statements? This parsing function sure works (with the right dictionaries), but it has to test 6 if-statements for each word in the input. For a 5-word sentence that would be 30 if-statements. It is also kind of hard to read.



def parse(text):
predicate=False
directObjectAdjective=False
directObject=False
preposition=False
indirectObjectAdjective=False
indirectObject=False
text=text.casefold()
text=text.split()
for word in text:
if not predicate:
if word in predicateDict:
predicate=predicateDict[word]
continue
if not directObjectAdjective:
if word in adjectiveDict:
directObjectAdjective=adjectiveDict[word]
continue
if not directObject:
if word in objectDict:
directObject=objectDict[word]
continue
if not preposition:
if word in prepositionDict:
preposition=prepositionDict[word]
continue
if not indirectObjectAdjective:
if word in adjectiveDict:
indirectObjectAdjective=adjectiveDict[word]
continue
if not indirectObject:
if word in objectDict:
indirectObject=objectDict[word]
continue
if not directObject and directObjectAdjective:
directObject=directObjectAdjective
directObjectAdjective=False
if not indirectObject and indirectObjectAdjective:
indirectObject=indirectObjectAdjective
indirectObjectAdjective=False
return [predicate,directObjectAdjective,directObject,preposition,indirectObjectAdjective,indirectObject]


Here's also a sample of a dictionary, if that's needed.



predicateDict=
"grab":"take",
"pick":"take",
"collect":"take",
"acquire":"take",
"snag":"take",
"gather":"take",
"attain":"take",
"capture":"take",
"take":"take"






python if-statement simplify simplification






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 17:36









lare290lare290

6




6












  • Does a switch statement work for your use case? jaxenter.com/implement-switch-case-statement-python-138315.html

    – Sam
    Mar 7 at 17:39











  • This pattern "if not something: if not word in someDict: something = someDict[word]" could be turned into a function.

    – Haroldo_OK
    Mar 7 at 17:43











  • From the performance side if you want only if to be executed then use elif rather than series of if

    – mad_
    Mar 7 at 17:48

















  • Does a switch statement work for your use case? jaxenter.com/implement-switch-case-statement-python-138315.html

    – Sam
    Mar 7 at 17:39











  • This pattern "if not something: if not word in someDict: something = someDict[word]" could be turned into a function.

    – Haroldo_OK
    Mar 7 at 17:43











  • From the performance side if you want only if to be executed then use elif rather than series of if

    – mad_
    Mar 7 at 17:48
















Does a switch statement work for your use case? jaxenter.com/implement-switch-case-statement-python-138315.html

– Sam
Mar 7 at 17:39





Does a switch statement work for your use case? jaxenter.com/implement-switch-case-statement-python-138315.html

– Sam
Mar 7 at 17:39













This pattern "if not something: if not word in someDict: something = someDict[word]" could be turned into a function.

– Haroldo_OK
Mar 7 at 17:43





This pattern "if not something: if not word in someDict: something = someDict[word]" could be turned into a function.

– Haroldo_OK
Mar 7 at 17:43













From the performance side if you want only if to be executed then use elif rather than series of if

– mad_
Mar 7 at 17:48





From the performance side if you want only if to be executed then use elif rather than series of if

– mad_
Mar 7 at 17:48












4 Answers
4






active

oldest

votes


















2














This is more of a Code Review question than a Stack Overflow one. A major issue is that you have similar data that you're keeping in separate variables. If you combine your variables, then you can iterate over them.



missing_parts_of_speech = ["predicate", [...]]
dict_look_up = "predicate":predicateDict,
[...]

found_parts_of_speech =
for word in text:
for part in missing_parts_of_speech:
if word in dict_look_up[part]:
found_parts_of_speech[part] = dict_look_up[part][word]
missing_parts_of_speech.remove(part)
continue





share|improve this answer























  • Basically the same as my idea, but using three dicts/lists instead of just one might indeed be better.

    – tobias_k
    Mar 7 at 18:10


















1














I would suggest to simply use the method dict.get. This method has the optional argument default. By passing this argument you can avoid a KeyError. If the key is not present in a dictionary, the default value will be returned.



If you use the previously assigned variable as default, it will not be replaced by an arbitrary value, but the correct value. E.g., if the current word is a "predicate" the "direct object" will be replaced by the value that was already stored in the variable.




CODE



def parse(text):
predicate = False
directObjectAdjective = False
directObject = False
preposition = False
indirectObjectAdjective = False
indirectObject = False

text=text.casefold()
text=text.split()
for word in text:
predicate = predicateDict.get(word, predicate)
directObjectAdjective = adjectiveDict.get(word, directObjectAdjective)
directObject = objectDict.get(word, directObject)
preposition = prepositionDict.get(word, preposition)
indirectObjectAdjective = adjectiveDict.get(word, indirectObjectAdjective)
indirectObject = objectDict.get(word, indirectObject)

if not directObject and directObjectAdjective:
directObject = directObjectAdjective
directObjectAdjective = False

if not indirectObject and indirectObjectAdjective:
indirectObject = indirectObjectAdjective
indirectObjectAdjective = False

return [predicate, directObjectAdjective, directObject, preposition, indirectObjectAdjective, indirectObject]



PS: Use a little more spaces. Readers will thank you...




PPS: I have not tested this, for I do not have such dictionaries at hand.




PPPS: This will always return the last occurances of the types within the text, while your implementation will always return the first occurances.






share|improve this answer
































    1














    You could map the different kinds of words (as strings) to dictionaries where to find those words, and then just check which of those have not been found yet and look them up if they are in those dicts.



    needed = "predicate": predicateDict,
    "directObjectAdjective": adjectiveDict,
    "directObject": objectDict,
    "preposition": prepositionDict,
    "indirectObjectAdjective": adjectiveDict,
    "indirectObject": objectDict

    for word in text:
    for kind in needed:
    if isinstance(needed[kind], dict) and word in needed[kind]:
    needed[kind] = needed[kind][word]
    continue


    In the end (and in each step on the way) all the items in needed that do not have a dict as a value have been found and replaced by the value from their respective dict.



    (In retrospect, it might make more sense to ue two dictionaries, or one dict and a set: One for the final value for that kind of word, and one for whether they have already been found. Would probably be a bit easier to grasp.)






    share|improve this answer






























      0














      I suggest that you use a new pattern to write this code instead the old one. The new pattern has 9 lines and stay 9 lines - just add more dictionaries to D. The old has already 11 lines and will grow 4 lines with every additional dictionaries to test.



      aDict = "a1" : "aa1", "a2" : "aa1" 
      bDict = "b1" : "bb1", "b2" : "bb2"
      text = ["a1", "b2", "a2", "b1"]
      # old pattern
      a = False
      b = False
      for word in text:
      if not a:
      if word in aDict:
      a = aDict[word]
      continue
      if not b:
      if word in bDict:
      b = bDict[word]
      continue
      print(a, b)
      # new pattern
      D = [ aDict, bDict]
      A = [ False for _ in D]
      for word in text:
      for i, a in enumerate(A):
      if not a:
      if word in D[i]:
      A[i] = D[i][word]
      continue
      print(A)





      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%2f55049811%2fsimplifying-many-if-statements%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        This is more of a Code Review question than a Stack Overflow one. A major issue is that you have similar data that you're keeping in separate variables. If you combine your variables, then you can iterate over them.



        missing_parts_of_speech = ["predicate", [...]]
        dict_look_up = "predicate":predicateDict,
        [...]

        found_parts_of_speech =
        for word in text:
        for part in missing_parts_of_speech:
        if word in dict_look_up[part]:
        found_parts_of_speech[part] = dict_look_up[part][word]
        missing_parts_of_speech.remove(part)
        continue





        share|improve this answer























        • Basically the same as my idea, but using three dicts/lists instead of just one might indeed be better.

          – tobias_k
          Mar 7 at 18:10















        2














        This is more of a Code Review question than a Stack Overflow one. A major issue is that you have similar data that you're keeping in separate variables. If you combine your variables, then you can iterate over them.



        missing_parts_of_speech = ["predicate", [...]]
        dict_look_up = "predicate":predicateDict,
        [...]

        found_parts_of_speech =
        for word in text:
        for part in missing_parts_of_speech:
        if word in dict_look_up[part]:
        found_parts_of_speech[part] = dict_look_up[part][word]
        missing_parts_of_speech.remove(part)
        continue





        share|improve this answer























        • Basically the same as my idea, but using three dicts/lists instead of just one might indeed be better.

          – tobias_k
          Mar 7 at 18:10













        2












        2








        2







        This is more of a Code Review question than a Stack Overflow one. A major issue is that you have similar data that you're keeping in separate variables. If you combine your variables, then you can iterate over them.



        missing_parts_of_speech = ["predicate", [...]]
        dict_look_up = "predicate":predicateDict,
        [...]

        found_parts_of_speech =
        for word in text:
        for part in missing_parts_of_speech:
        if word in dict_look_up[part]:
        found_parts_of_speech[part] = dict_look_up[part][word]
        missing_parts_of_speech.remove(part)
        continue





        share|improve this answer













        This is more of a Code Review question than a Stack Overflow one. A major issue is that you have similar data that you're keeping in separate variables. If you combine your variables, then you can iterate over them.



        missing_parts_of_speech = ["predicate", [...]]
        dict_look_up = "predicate":predicateDict,
        [...]

        found_parts_of_speech =
        for word in text:
        for part in missing_parts_of_speech:
        if word in dict_look_up[part]:
        found_parts_of_speech[part] = dict_look_up[part][word]
        missing_parts_of_speech.remove(part)
        continue






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 7 at 18:07









        AcccumulationAcccumulation

        1,44329




        1,44329












        • Basically the same as my idea, but using three dicts/lists instead of just one might indeed be better.

          – tobias_k
          Mar 7 at 18:10

















        • Basically the same as my idea, but using three dicts/lists instead of just one might indeed be better.

          – tobias_k
          Mar 7 at 18:10
















        Basically the same as my idea, but using three dicts/lists instead of just one might indeed be better.

        – tobias_k
        Mar 7 at 18:10





        Basically the same as my idea, but using three dicts/lists instead of just one might indeed be better.

        – tobias_k
        Mar 7 at 18:10













        1














        I would suggest to simply use the method dict.get. This method has the optional argument default. By passing this argument you can avoid a KeyError. If the key is not present in a dictionary, the default value will be returned.



        If you use the previously assigned variable as default, it will not be replaced by an arbitrary value, but the correct value. E.g., if the current word is a "predicate" the "direct object" will be replaced by the value that was already stored in the variable.




        CODE



        def parse(text):
        predicate = False
        directObjectAdjective = False
        directObject = False
        preposition = False
        indirectObjectAdjective = False
        indirectObject = False

        text=text.casefold()
        text=text.split()
        for word in text:
        predicate = predicateDict.get(word, predicate)
        directObjectAdjective = adjectiveDict.get(word, directObjectAdjective)
        directObject = objectDict.get(word, directObject)
        preposition = prepositionDict.get(word, preposition)
        indirectObjectAdjective = adjectiveDict.get(word, indirectObjectAdjective)
        indirectObject = objectDict.get(word, indirectObject)

        if not directObject and directObjectAdjective:
        directObject = directObjectAdjective
        directObjectAdjective = False

        if not indirectObject and indirectObjectAdjective:
        indirectObject = indirectObjectAdjective
        indirectObjectAdjective = False

        return [predicate, directObjectAdjective, directObject, preposition, indirectObjectAdjective, indirectObject]



        PS: Use a little more spaces. Readers will thank you...




        PPS: I have not tested this, for I do not have such dictionaries at hand.




        PPPS: This will always return the last occurances of the types within the text, while your implementation will always return the first occurances.






        share|improve this answer





























          1














          I would suggest to simply use the method dict.get. This method has the optional argument default. By passing this argument you can avoid a KeyError. If the key is not present in a dictionary, the default value will be returned.



          If you use the previously assigned variable as default, it will not be replaced by an arbitrary value, but the correct value. E.g., if the current word is a "predicate" the "direct object" will be replaced by the value that was already stored in the variable.




          CODE



          def parse(text):
          predicate = False
          directObjectAdjective = False
          directObject = False
          preposition = False
          indirectObjectAdjective = False
          indirectObject = False

          text=text.casefold()
          text=text.split()
          for word in text:
          predicate = predicateDict.get(word, predicate)
          directObjectAdjective = adjectiveDict.get(word, directObjectAdjective)
          directObject = objectDict.get(word, directObject)
          preposition = prepositionDict.get(word, preposition)
          indirectObjectAdjective = adjectiveDict.get(word, indirectObjectAdjective)
          indirectObject = objectDict.get(word, indirectObject)

          if not directObject and directObjectAdjective:
          directObject = directObjectAdjective
          directObjectAdjective = False

          if not indirectObject and indirectObjectAdjective:
          indirectObject = indirectObjectAdjective
          indirectObjectAdjective = False

          return [predicate, directObjectAdjective, directObject, preposition, indirectObjectAdjective, indirectObject]



          PS: Use a little more spaces. Readers will thank you...




          PPS: I have not tested this, for I do not have such dictionaries at hand.




          PPPS: This will always return the last occurances of the types within the text, while your implementation will always return the first occurances.






          share|improve this answer



























            1












            1








            1







            I would suggest to simply use the method dict.get. This method has the optional argument default. By passing this argument you can avoid a KeyError. If the key is not present in a dictionary, the default value will be returned.



            If you use the previously assigned variable as default, it will not be replaced by an arbitrary value, but the correct value. E.g., if the current word is a "predicate" the "direct object" will be replaced by the value that was already stored in the variable.




            CODE



            def parse(text):
            predicate = False
            directObjectAdjective = False
            directObject = False
            preposition = False
            indirectObjectAdjective = False
            indirectObject = False

            text=text.casefold()
            text=text.split()
            for word in text:
            predicate = predicateDict.get(word, predicate)
            directObjectAdjective = adjectiveDict.get(word, directObjectAdjective)
            directObject = objectDict.get(word, directObject)
            preposition = prepositionDict.get(word, preposition)
            indirectObjectAdjective = adjectiveDict.get(word, indirectObjectAdjective)
            indirectObject = objectDict.get(word, indirectObject)

            if not directObject and directObjectAdjective:
            directObject = directObjectAdjective
            directObjectAdjective = False

            if not indirectObject and indirectObjectAdjective:
            indirectObject = indirectObjectAdjective
            indirectObjectAdjective = False

            return [predicate, directObjectAdjective, directObject, preposition, indirectObjectAdjective, indirectObject]



            PS: Use a little more spaces. Readers will thank you...




            PPS: I have not tested this, for I do not have such dictionaries at hand.




            PPPS: This will always return the last occurances of the types within the text, while your implementation will always return the first occurances.






            share|improve this answer















            I would suggest to simply use the method dict.get. This method has the optional argument default. By passing this argument you can avoid a KeyError. If the key is not present in a dictionary, the default value will be returned.



            If you use the previously assigned variable as default, it will not be replaced by an arbitrary value, but the correct value. E.g., if the current word is a "predicate" the "direct object" will be replaced by the value that was already stored in the variable.




            CODE



            def parse(text):
            predicate = False
            directObjectAdjective = False
            directObject = False
            preposition = False
            indirectObjectAdjective = False
            indirectObject = False

            text=text.casefold()
            text=text.split()
            for word in text:
            predicate = predicateDict.get(word, predicate)
            directObjectAdjective = adjectiveDict.get(word, directObjectAdjective)
            directObject = objectDict.get(word, directObject)
            preposition = prepositionDict.get(word, preposition)
            indirectObjectAdjective = adjectiveDict.get(word, indirectObjectAdjective)
            indirectObject = objectDict.get(word, indirectObject)

            if not directObject and directObjectAdjective:
            directObject = directObjectAdjective
            directObjectAdjective = False

            if not indirectObject and indirectObjectAdjective:
            indirectObject = indirectObjectAdjective
            indirectObjectAdjective = False

            return [predicate, directObjectAdjective, directObject, preposition, indirectObjectAdjective, indirectObject]



            PS: Use a little more spaces. Readers will thank you...




            PPS: I have not tested this, for I do not have such dictionaries at hand.




            PPPS: This will always return the last occurances of the types within the text, while your implementation will always return the first occurances.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 7 at 18:04

























            answered Mar 7 at 17:50









            Sven KrügerSven Krüger

            657513




            657513





















                1














                You could map the different kinds of words (as strings) to dictionaries where to find those words, and then just check which of those have not been found yet and look them up if they are in those dicts.



                needed = "predicate": predicateDict,
                "directObjectAdjective": adjectiveDict,
                "directObject": objectDict,
                "preposition": prepositionDict,
                "indirectObjectAdjective": adjectiveDict,
                "indirectObject": objectDict

                for word in text:
                for kind in needed:
                if isinstance(needed[kind], dict) and word in needed[kind]:
                needed[kind] = needed[kind][word]
                continue


                In the end (and in each step on the way) all the items in needed that do not have a dict as a value have been found and replaced by the value from their respective dict.



                (In retrospect, it might make more sense to ue two dictionaries, or one dict and a set: One for the final value for that kind of word, and one for whether they have already been found. Would probably be a bit easier to grasp.)






                share|improve this answer



























                  1














                  You could map the different kinds of words (as strings) to dictionaries where to find those words, and then just check which of those have not been found yet and look them up if they are in those dicts.



                  needed = "predicate": predicateDict,
                  "directObjectAdjective": adjectiveDict,
                  "directObject": objectDict,
                  "preposition": prepositionDict,
                  "indirectObjectAdjective": adjectiveDict,
                  "indirectObject": objectDict

                  for word in text:
                  for kind in needed:
                  if isinstance(needed[kind], dict) and word in needed[kind]:
                  needed[kind] = needed[kind][word]
                  continue


                  In the end (and in each step on the way) all the items in needed that do not have a dict as a value have been found and replaced by the value from their respective dict.



                  (In retrospect, it might make more sense to ue two dictionaries, or one dict and a set: One for the final value for that kind of word, and one for whether they have already been found. Would probably be a bit easier to grasp.)






                  share|improve this answer

























                    1












                    1








                    1







                    You could map the different kinds of words (as strings) to dictionaries where to find those words, and then just check which of those have not been found yet and look them up if they are in those dicts.



                    needed = "predicate": predicateDict,
                    "directObjectAdjective": adjectiveDict,
                    "directObject": objectDict,
                    "preposition": prepositionDict,
                    "indirectObjectAdjective": adjectiveDict,
                    "indirectObject": objectDict

                    for word in text:
                    for kind in needed:
                    if isinstance(needed[kind], dict) and word in needed[kind]:
                    needed[kind] = needed[kind][word]
                    continue


                    In the end (and in each step on the way) all the items in needed that do not have a dict as a value have been found and replaced by the value from their respective dict.



                    (In retrospect, it might make more sense to ue two dictionaries, or one dict and a set: One for the final value for that kind of word, and one for whether they have already been found. Would probably be a bit easier to grasp.)






                    share|improve this answer













                    You could map the different kinds of words (as strings) to dictionaries where to find those words, and then just check which of those have not been found yet and look them up if they are in those dicts.



                    needed = "predicate": predicateDict,
                    "directObjectAdjective": adjectiveDict,
                    "directObject": objectDict,
                    "preposition": prepositionDict,
                    "indirectObjectAdjective": adjectiveDict,
                    "indirectObject": objectDict

                    for word in text:
                    for kind in needed:
                    if isinstance(needed[kind], dict) and word in needed[kind]:
                    needed[kind] = needed[kind][word]
                    continue


                    In the end (and in each step on the way) all the items in needed that do not have a dict as a value have been found and replaced by the value from their respective dict.



                    (In retrospect, it might make more sense to ue two dictionaries, or one dict and a set: One for the final value for that kind of word, and one for whether they have already been found. Would probably be a bit easier to grasp.)







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 7 at 18:05









                    tobias_ktobias_k

                    59.2k971110




                    59.2k971110





















                        0














                        I suggest that you use a new pattern to write this code instead the old one. The new pattern has 9 lines and stay 9 lines - just add more dictionaries to D. The old has already 11 lines and will grow 4 lines with every additional dictionaries to test.



                        aDict = "a1" : "aa1", "a2" : "aa1" 
                        bDict = "b1" : "bb1", "b2" : "bb2"
                        text = ["a1", "b2", "a2", "b1"]
                        # old pattern
                        a = False
                        b = False
                        for word in text:
                        if not a:
                        if word in aDict:
                        a = aDict[word]
                        continue
                        if not b:
                        if word in bDict:
                        b = bDict[word]
                        continue
                        print(a, b)
                        # new pattern
                        D = [ aDict, bDict]
                        A = [ False for _ in D]
                        for word in text:
                        for i, a in enumerate(A):
                        if not a:
                        if word in D[i]:
                        A[i] = D[i][word]
                        continue
                        print(A)





                        share|improve this answer



























                          0














                          I suggest that you use a new pattern to write this code instead the old one. The new pattern has 9 lines and stay 9 lines - just add more dictionaries to D. The old has already 11 lines and will grow 4 lines with every additional dictionaries to test.



                          aDict = "a1" : "aa1", "a2" : "aa1" 
                          bDict = "b1" : "bb1", "b2" : "bb2"
                          text = ["a1", "b2", "a2", "b1"]
                          # old pattern
                          a = False
                          b = False
                          for word in text:
                          if not a:
                          if word in aDict:
                          a = aDict[word]
                          continue
                          if not b:
                          if word in bDict:
                          b = bDict[word]
                          continue
                          print(a, b)
                          # new pattern
                          D = [ aDict, bDict]
                          A = [ False for _ in D]
                          for word in text:
                          for i, a in enumerate(A):
                          if not a:
                          if word in D[i]:
                          A[i] = D[i][word]
                          continue
                          print(A)





                          share|improve this answer

























                            0












                            0








                            0







                            I suggest that you use a new pattern to write this code instead the old one. The new pattern has 9 lines and stay 9 lines - just add more dictionaries to D. The old has already 11 lines and will grow 4 lines with every additional dictionaries to test.



                            aDict = "a1" : "aa1", "a2" : "aa1" 
                            bDict = "b1" : "bb1", "b2" : "bb2"
                            text = ["a1", "b2", "a2", "b1"]
                            # old pattern
                            a = False
                            b = False
                            for word in text:
                            if not a:
                            if word in aDict:
                            a = aDict[word]
                            continue
                            if not b:
                            if word in bDict:
                            b = bDict[word]
                            continue
                            print(a, b)
                            # new pattern
                            D = [ aDict, bDict]
                            A = [ False for _ in D]
                            for word in text:
                            for i, a in enumerate(A):
                            if not a:
                            if word in D[i]:
                            A[i] = D[i][word]
                            continue
                            print(A)





                            share|improve this answer













                            I suggest that you use a new pattern to write this code instead the old one. The new pattern has 9 lines and stay 9 lines - just add more dictionaries to D. The old has already 11 lines and will grow 4 lines with every additional dictionaries to test.



                            aDict = "a1" : "aa1", "a2" : "aa1" 
                            bDict = "b1" : "bb1", "b2" : "bb2"
                            text = ["a1", "b2", "a2", "b1"]
                            # old pattern
                            a = False
                            b = False
                            for word in text:
                            if not a:
                            if word in aDict:
                            a = aDict[word]
                            continue
                            if not b:
                            if word in bDict:
                            b = bDict[word]
                            continue
                            print(a, b)
                            # new pattern
                            D = [ aDict, bDict]
                            A = [ False for _ in D]
                            for word in text:
                            for i, a in enumerate(A):
                            if not a:
                            if word in D[i]:
                            A[i] = D[i][word]
                            continue
                            print(A)






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 7 at 18:22









                            Alexander LopatinAlexander Lopatin

                            1807




                            1807



























                                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%2f55049811%2fsimplifying-many-if-statements%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

                                Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                                Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                                Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved