file in python formatting





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-3















So here is a file



APPLE: toronto, 2018, garden, tasty, 5
apple is a tasty fruit
>>>end
Orange: japan, 32, home, sour, 1
orange is a sour fruit
>>>end
graEes: america, 24, organic, sweet, 4
grapes is a sweet fruit
>>>end


This is a file which also has new line characters.
I want tp create a dictionary using the file. it goes like this



the function is def f(file_to: (TextIO))-> Dict[str, List[tuple]]



file_to is file name entered and it will return the dictionary like,



{'apple': ['apple is a tasty fruit', 2018, 'garden', 'tasty', 5], orange:['orange is a sour fruit', 32,'home', 'sour',1] then grapes......}


each of the fruit is key and their discription is values as formatted there. Each fruits ends at >>>end



I tried



with open (file_to, "r") as myfile:
data= myfile.readlines()
return data


it returns the file strings in a list with /n I'm thinking I can use strip() to remove that and get the element that comes before ':' as keys.










share|improve this question































    -3















    So here is a file



    APPLE: toronto, 2018, garden, tasty, 5
    apple is a tasty fruit
    >>>end
    Orange: japan, 32, home, sour, 1
    orange is a sour fruit
    >>>end
    graEes: america, 24, organic, sweet, 4
    grapes is a sweet fruit
    >>>end


    This is a file which also has new line characters.
    I want tp create a dictionary using the file. it goes like this



    the function is def f(file_to: (TextIO))-> Dict[str, List[tuple]]



    file_to is file name entered and it will return the dictionary like,



    {'apple': ['apple is a tasty fruit', 2018, 'garden', 'tasty', 5], orange:['orange is a sour fruit', 32,'home', 'sour',1] then grapes......}


    each of the fruit is key and their discription is values as formatted there. Each fruits ends at >>>end



    I tried



    with open (file_to, "r") as myfile:
    data= myfile.readlines()
    return data


    it returns the file strings in a list with /n I'm thinking I can use strip() to remove that and get the element that comes before ':' as keys.










    share|improve this question



























      -3












      -3








      -3








      So here is a file



      APPLE: toronto, 2018, garden, tasty, 5
      apple is a tasty fruit
      >>>end
      Orange: japan, 32, home, sour, 1
      orange is a sour fruit
      >>>end
      graEes: america, 24, organic, sweet, 4
      grapes is a sweet fruit
      >>>end


      This is a file which also has new line characters.
      I want tp create a dictionary using the file. it goes like this



      the function is def f(file_to: (TextIO))-> Dict[str, List[tuple]]



      file_to is file name entered and it will return the dictionary like,



      {'apple': ['apple is a tasty fruit', 2018, 'garden', 'tasty', 5], orange:['orange is a sour fruit', 32,'home', 'sour',1] then grapes......}


      each of the fruit is key and their discription is values as formatted there. Each fruits ends at >>>end



      I tried



      with open (file_to, "r") as myfile:
      data= myfile.readlines()
      return data


      it returns the file strings in a list with /n I'm thinking I can use strip() to remove that and get the element that comes before ':' as keys.










      share|improve this question
















      So here is a file



      APPLE: toronto, 2018, garden, tasty, 5
      apple is a tasty fruit
      >>>end
      Orange: japan, 32, home, sour, 1
      orange is a sour fruit
      >>>end
      graEes: america, 24, organic, sweet, 4
      grapes is a sweet fruit
      >>>end


      This is a file which also has new line characters.
      I want tp create a dictionary using the file. it goes like this



      the function is def f(file_to: (TextIO))-> Dict[str, List[tuple]]



      file_to is file name entered and it will return the dictionary like,



      {'apple': ['apple is a tasty fruit', 2018, 'garden', 'tasty', 5], orange:['orange is a sour fruit', 32,'home', 'sour',1] then grapes......}


      each of the fruit is key and their discription is values as formatted there. Each fruits ends at >>>end



      I tried



      with open (file_to, "r") as myfile:
      data= myfile.readlines()
      return data


      it returns the file strings in a list with /n I'm thinking I can use strip() to remove that and get the element that comes before ':' as keys.







      python dictionary






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 28 '18 at 17:07







      Comp

















      asked Nov 23 '18 at 1:51









      CompComp

      456




      456
























          1 Answer
          1






          active

          oldest

          votes


















          2














          For this simple example, the following gives the results you want. (Although you probably misspelled grapes).



          from pprint import pprint
          import re

          def main():
          fin = open('f1.txt', 'r')

          data = {}
          key = ''
          parsed =
          for line in fin:
          line = line.rstrip()
          if line.startswith('>'):
          data[key] = parsed
          parsed =
          elif ':' in line:
          parts = re.split('W+', line)
          key = parts[0].lower()
          parsed += parts[2:]
          else:
          parsed.insert(0, line)

          fin.close()
          pprint(data)


          main()





          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%2f53439791%2ffile-in-python-formatting%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            For this simple example, the following gives the results you want. (Although you probably misspelled grapes).



            from pprint import pprint
            import re

            def main():
            fin = open('f1.txt', 'r')

            data = {}
            key = ''
            parsed =
            for line in fin:
            line = line.rstrip()
            if line.startswith('>'):
            data[key] = parsed
            parsed =
            elif ':' in line:
            parts = re.split('W+', line)
            key = parts[0].lower()
            parsed += parts[2:]
            else:
            parsed.insert(0, line)

            fin.close()
            pprint(data)


            main()





            share|improve this answer






























              2














              For this simple example, the following gives the results you want. (Although you probably misspelled grapes).



              from pprint import pprint
              import re

              def main():
              fin = open('f1.txt', 'r')

              data = {}
              key = ''
              parsed =
              for line in fin:
              line = line.rstrip()
              if line.startswith('>'):
              data[key] = parsed
              parsed =
              elif ':' in line:
              parts = re.split('W+', line)
              key = parts[0].lower()
              parsed += parts[2:]
              else:
              parsed.insert(0, line)

              fin.close()
              pprint(data)


              main()





              share|improve this answer




























                2












                2








                2







                For this simple example, the following gives the results you want. (Although you probably misspelled grapes).



                from pprint import pprint
                import re

                def main():
                fin = open('f1.txt', 'r')

                data = {}
                key = ''
                parsed =
                for line in fin:
                line = line.rstrip()
                if line.startswith('>'):
                data[key] = parsed
                parsed =
                elif ':' in line:
                parts = re.split('W+', line)
                key = parts[0].lower()
                parsed += parts[2:]
                else:
                parsed.insert(0, line)

                fin.close()
                pprint(data)


                main()





                share|improve this answer















                For this simple example, the following gives the results you want. (Although you probably misspelled grapes).



                from pprint import pprint
                import re

                def main():
                fin = open('f1.txt', 'r')

                data = {}
                key = ''
                parsed =
                for line in fin:
                line = line.rstrip()
                if line.startswith('>'):
                data[key] = parsed
                parsed =
                elif ':' in line:
                parts = re.split('W+', line)
                key = parts[0].lower()
                parsed += parts[2:]
                else:
                parsed.insert(0, line)

                fin.close()
                pprint(data)


                main()






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 23 '18 at 3:01

























                answered Nov 23 '18 at 2:53









                Chris CharleyChris Charley

                3,86021619




                3,86021619
































                    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%2f53439791%2ffile-in-python-formatting%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

                    How to change which sound is reproduced for terminal bell?

                    Can I use Tabulator js library in my java Spring + Thymeleaf project?

                    Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents