Turn a file into dictionary











up vote
-3
down vote

favorite












I'm really new into Python and I have a question. I need to convert a file containing morse code alphabet. It's a file with a single string and it looks like this (A2.-B4-...C4-.-.D3-..). I'm thinking that I should be able to create a dictionary out of this file but I'm not sure how. Do you guys have any idea?










share|improve this question




















  • 7




    Welcome to Stackoverflow! Would you like to post some data formatted as they are in your file and give us an example of desired output?
    – Vasilis G.
    Nov 7 at 16:25










  • I can't see your screen from here, can you post what you have tried, what the file looks like, what you want the output to be, what you want the directory to be?
    – SPYBUG96
    Nov 7 at 16:28















up vote
-3
down vote

favorite












I'm really new into Python and I have a question. I need to convert a file containing morse code alphabet. It's a file with a single string and it looks like this (A2.-B4-...C4-.-.D3-..). I'm thinking that I should be able to create a dictionary out of this file but I'm not sure how. Do you guys have any idea?










share|improve this question




















  • 7




    Welcome to Stackoverflow! Would you like to post some data formatted as they are in your file and give us an example of desired output?
    – Vasilis G.
    Nov 7 at 16:25










  • I can't see your screen from here, can you post what you have tried, what the file looks like, what you want the output to be, what you want the directory to be?
    – SPYBUG96
    Nov 7 at 16:28













up vote
-3
down vote

favorite









up vote
-3
down vote

favorite











I'm really new into Python and I have a question. I need to convert a file containing morse code alphabet. It's a file with a single string and it looks like this (A2.-B4-...C4-.-.D3-..). I'm thinking that I should be able to create a dictionary out of this file but I'm not sure how. Do you guys have any idea?










share|improve this question















I'm really new into Python and I have a question. I need to convert a file containing morse code alphabet. It's a file with a single string and it looks like this (A2.-B4-...C4-.-.D3-..). I'm thinking that I should be able to create a dictionary out of this file but I'm not sure how. Do you guys have any idea?







python file dictionary






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 7 at 16:44









nosklo

150k46247268




150k46247268










asked Nov 7 at 16:23









gdom

1




1








  • 7




    Welcome to Stackoverflow! Would you like to post some data formatted as they are in your file and give us an example of desired output?
    – Vasilis G.
    Nov 7 at 16:25










  • I can't see your screen from here, can you post what you have tried, what the file looks like, what you want the output to be, what you want the directory to be?
    – SPYBUG96
    Nov 7 at 16:28














  • 7




    Welcome to Stackoverflow! Would you like to post some data formatted as they are in your file and give us an example of desired output?
    – Vasilis G.
    Nov 7 at 16:25










  • I can't see your screen from here, can you post what you have tried, what the file looks like, what you want the output to be, what you want the directory to be?
    – SPYBUG96
    Nov 7 at 16:28








7




7




Welcome to Stackoverflow! Would you like to post some data formatted as they are in your file and give us an example of desired output?
– Vasilis G.
Nov 7 at 16:25




Welcome to Stackoverflow! Would you like to post some data formatted as they are in your file and give us an example of desired output?
– Vasilis G.
Nov 7 at 16:25












I can't see your screen from here, can you post what you have tried, what the file looks like, what you want the output to be, what you want the directory to be?
– SPYBUG96
Nov 7 at 16:28




I can't see your screen from here, can you post what you have tried, what the file looks like, what you want the output to be, what you want the directory to be?
– SPYBUG96
Nov 7 at 16:28












2 Answers
2






active

oldest

votes

















up vote
0
down vote













This approach uses regular expression to parse your entire string and convert it to dict directly:



import re

with open('yourfile.txt') as f:
data = f.read()

morse = dict(re.findall(r'(w)d+([-.]+)', data))
print(morse)


The results for your example data:



{'A': '.-', 'C': '-.-.', 'B': '-...', 'D': '-..'}


Here's a short explanation of the regular expression:





  • (w) parens means we want to capture this part, w means any alphanumeric


  • d+ here, d means any digit and the + sign means one or more


  • ([-.]+) parens again means we want to capture this part, [-.] means we want . or - and the + again means we want one or more of those.


For more regular expression explanation I suggest reading "Regular Expression HOWTO" by A. M. Kuchling, excellent read.






share|improve this answer























  • Wow, this looks really elegant! I've never heard about regular expression... but it looks like a really good tool to handle different patterns in text. I've tried google to understand what r'(w)d+([-.]+)' means but I don't fully understand it. Could you please explain what different parts of mention code mean? I'm really thankful for your help :)
    – gdom
    Nov 8 at 11:14










  • @gdom I have added a short explanation of the regular expression, and a link to a more detailed regular expression text for beginners. If my answer is good for you, please consider marking it as accepted to close the question.
    – nosklo
    Nov 8 at 14:40


















up vote
-1
down vote













When you open files in Python, they can be read line by line like so:



d = {} # Init empty dict
with open("file.txt", "r") as file: # This manages the open/close, IO mode, et cetera
for line in file: # Iterates through the file line by line
# Now the variable line represents a string for that line
sline = line.split("-")
d[sline[0]] = sline[1]


In the last two lines of this example I assume that you want a dict where the key (lookup) always sits before "-" on each line, and the value (to be looked up) is always after. On this assumption I line.split("-") and then assign those keys and values to dict d with d[sline[0]] = sline[1]. If you adopt this solution but have problems with this part of the solution, I think that might warrant a separate question.






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',
    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%2f53193634%2fturn-a-file-into-dictionary%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








    up vote
    0
    down vote













    This approach uses regular expression to parse your entire string and convert it to dict directly:



    import re

    with open('yourfile.txt') as f:
    data = f.read()

    morse = dict(re.findall(r'(w)d+([-.]+)', data))
    print(morse)


    The results for your example data:



    {'A': '.-', 'C': '-.-.', 'B': '-...', 'D': '-..'}


    Here's a short explanation of the regular expression:





    • (w) parens means we want to capture this part, w means any alphanumeric


    • d+ here, d means any digit and the + sign means one or more


    • ([-.]+) parens again means we want to capture this part, [-.] means we want . or - and the + again means we want one or more of those.


    For more regular expression explanation I suggest reading "Regular Expression HOWTO" by A. M. Kuchling, excellent read.






    share|improve this answer























    • Wow, this looks really elegant! I've never heard about regular expression... but it looks like a really good tool to handle different patterns in text. I've tried google to understand what r'(w)d+([-.]+)' means but I don't fully understand it. Could you please explain what different parts of mention code mean? I'm really thankful for your help :)
      – gdom
      Nov 8 at 11:14










    • @gdom I have added a short explanation of the regular expression, and a link to a more detailed regular expression text for beginners. If my answer is good for you, please consider marking it as accepted to close the question.
      – nosklo
      Nov 8 at 14:40















    up vote
    0
    down vote













    This approach uses regular expression to parse your entire string and convert it to dict directly:



    import re

    with open('yourfile.txt') as f:
    data = f.read()

    morse = dict(re.findall(r'(w)d+([-.]+)', data))
    print(morse)


    The results for your example data:



    {'A': '.-', 'C': '-.-.', 'B': '-...', 'D': '-..'}


    Here's a short explanation of the regular expression:





    • (w) parens means we want to capture this part, w means any alphanumeric


    • d+ here, d means any digit and the + sign means one or more


    • ([-.]+) parens again means we want to capture this part, [-.] means we want . or - and the + again means we want one or more of those.


    For more regular expression explanation I suggest reading "Regular Expression HOWTO" by A. M. Kuchling, excellent read.






    share|improve this answer























    • Wow, this looks really elegant! I've never heard about regular expression... but it looks like a really good tool to handle different patterns in text. I've tried google to understand what r'(w)d+([-.]+)' means but I don't fully understand it. Could you please explain what different parts of mention code mean? I'm really thankful for your help :)
      – gdom
      Nov 8 at 11:14










    • @gdom I have added a short explanation of the regular expression, and a link to a more detailed regular expression text for beginners. If my answer is good for you, please consider marking it as accepted to close the question.
      – nosklo
      Nov 8 at 14:40













    up vote
    0
    down vote










    up vote
    0
    down vote









    This approach uses regular expression to parse your entire string and convert it to dict directly:



    import re

    with open('yourfile.txt') as f:
    data = f.read()

    morse = dict(re.findall(r'(w)d+([-.]+)', data))
    print(morse)


    The results for your example data:



    {'A': '.-', 'C': '-.-.', 'B': '-...', 'D': '-..'}


    Here's a short explanation of the regular expression:





    • (w) parens means we want to capture this part, w means any alphanumeric


    • d+ here, d means any digit and the + sign means one or more


    • ([-.]+) parens again means we want to capture this part, [-.] means we want . or - and the + again means we want one or more of those.


    For more regular expression explanation I suggest reading "Regular Expression HOWTO" by A. M. Kuchling, excellent read.






    share|improve this answer














    This approach uses regular expression to parse your entire string and convert it to dict directly:



    import re

    with open('yourfile.txt') as f:
    data = f.read()

    morse = dict(re.findall(r'(w)d+([-.]+)', data))
    print(morse)


    The results for your example data:



    {'A': '.-', 'C': '-.-.', 'B': '-...', 'D': '-..'}


    Here's a short explanation of the regular expression:





    • (w) parens means we want to capture this part, w means any alphanumeric


    • d+ here, d means any digit and the + sign means one or more


    • ([-.]+) parens again means we want to capture this part, [-.] means we want . or - and the + again means we want one or more of those.


    For more regular expression explanation I suggest reading "Regular Expression HOWTO" by A. M. Kuchling, excellent read.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 8 at 14:39

























    answered Nov 7 at 16:42









    nosklo

    150k46247268




    150k46247268












    • Wow, this looks really elegant! I've never heard about regular expression... but it looks like a really good tool to handle different patterns in text. I've tried google to understand what r'(w)d+([-.]+)' means but I don't fully understand it. Could you please explain what different parts of mention code mean? I'm really thankful for your help :)
      – gdom
      Nov 8 at 11:14










    • @gdom I have added a short explanation of the regular expression, and a link to a more detailed regular expression text for beginners. If my answer is good for you, please consider marking it as accepted to close the question.
      – nosklo
      Nov 8 at 14:40


















    • Wow, this looks really elegant! I've never heard about regular expression... but it looks like a really good tool to handle different patterns in text. I've tried google to understand what r'(w)d+([-.]+)' means but I don't fully understand it. Could you please explain what different parts of mention code mean? I'm really thankful for your help :)
      – gdom
      Nov 8 at 11:14










    • @gdom I have added a short explanation of the regular expression, and a link to a more detailed regular expression text for beginners. If my answer is good for you, please consider marking it as accepted to close the question.
      – nosklo
      Nov 8 at 14:40
















    Wow, this looks really elegant! I've never heard about regular expression... but it looks like a really good tool to handle different patterns in text. I've tried google to understand what r'(w)d+([-.]+)' means but I don't fully understand it. Could you please explain what different parts of mention code mean? I'm really thankful for your help :)
    – gdom
    Nov 8 at 11:14




    Wow, this looks really elegant! I've never heard about regular expression... but it looks like a really good tool to handle different patterns in text. I've tried google to understand what r'(w)d+([-.]+)' means but I don't fully understand it. Could you please explain what different parts of mention code mean? I'm really thankful for your help :)
    – gdom
    Nov 8 at 11:14












    @gdom I have added a short explanation of the regular expression, and a link to a more detailed regular expression text for beginners. If my answer is good for you, please consider marking it as accepted to close the question.
    – nosklo
    Nov 8 at 14:40




    @gdom I have added a short explanation of the regular expression, and a link to a more detailed regular expression text for beginners. If my answer is good for you, please consider marking it as accepted to close the question.
    – nosklo
    Nov 8 at 14:40












    up vote
    -1
    down vote













    When you open files in Python, they can be read line by line like so:



    d = {} # Init empty dict
    with open("file.txt", "r") as file: # This manages the open/close, IO mode, et cetera
    for line in file: # Iterates through the file line by line
    # Now the variable line represents a string for that line
    sline = line.split("-")
    d[sline[0]] = sline[1]


    In the last two lines of this example I assume that you want a dict where the key (lookup) always sits before "-" on each line, and the value (to be looked up) is always after. On this assumption I line.split("-") and then assign those keys and values to dict d with d[sline[0]] = sline[1]. If you adopt this solution but have problems with this part of the solution, I think that might warrant a separate question.






    share|improve this answer

























      up vote
      -1
      down vote













      When you open files in Python, they can be read line by line like so:



      d = {} # Init empty dict
      with open("file.txt", "r") as file: # This manages the open/close, IO mode, et cetera
      for line in file: # Iterates through the file line by line
      # Now the variable line represents a string for that line
      sline = line.split("-")
      d[sline[0]] = sline[1]


      In the last two lines of this example I assume that you want a dict where the key (lookup) always sits before "-" on each line, and the value (to be looked up) is always after. On this assumption I line.split("-") and then assign those keys and values to dict d with d[sline[0]] = sline[1]. If you adopt this solution but have problems with this part of the solution, I think that might warrant a separate question.






      share|improve this answer























        up vote
        -1
        down vote










        up vote
        -1
        down vote









        When you open files in Python, they can be read line by line like so:



        d = {} # Init empty dict
        with open("file.txt", "r") as file: # This manages the open/close, IO mode, et cetera
        for line in file: # Iterates through the file line by line
        # Now the variable line represents a string for that line
        sline = line.split("-")
        d[sline[0]] = sline[1]


        In the last two lines of this example I assume that you want a dict where the key (lookup) always sits before "-" on each line, and the value (to be looked up) is always after. On this assumption I line.split("-") and then assign those keys and values to dict d with d[sline[0]] = sline[1]. If you adopt this solution but have problems with this part of the solution, I think that might warrant a separate question.






        share|improve this answer












        When you open files in Python, they can be read line by line like so:



        d = {} # Init empty dict
        with open("file.txt", "r") as file: # This manages the open/close, IO mode, et cetera
        for line in file: # Iterates through the file line by line
        # Now the variable line represents a string for that line
        sline = line.split("-")
        d[sline[0]] = sline[1]


        In the last two lines of this example I assume that you want a dict where the key (lookup) always sits before "-" on each line, and the value (to be looked up) is always after. On this assumption I line.split("-") and then assign those keys and values to dict d with d[sline[0]] = sline[1]. If you adopt this solution but have problems with this part of the solution, I think that might warrant a separate question.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 7 at 16:40









        Charles Landau

        1,1401211




        1,1401211






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53193634%2fturn-a-file-into-dictionary%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







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()