Search code examples
pythonautomationscripting

How to get just the first word of every line of file using python?


as you can see i'm a newbie and i don't know how to ask this question so i'm going to explain. i was writing Somali dictionary in text format and i have a lot of words and their meaning, so i want to have those words only not their meaning in another text format file in order to have a list of only vocabulary. Is their a way i can do that. Example "abaabid m.dh eeg abaab². ld ababid. ld abaab¹, abaabis." I have hundred of these words and their meaning and i want to pick only the word "abaabid" and etc. so how can i automate it in python instead of copy pasting manually all day?. Stop saying post the code as text, i don't even know how to write the code and that's why i'm asking this question. This screenshot is the text file showing words with their meaning.


Solution

  • If you just want a script to read the dictionary entries and then write the words into a separate file, try something like this:

    
    def get_words(filename='Somali Dictionary.txt'):
        with open(filename, 'r') as f:
            lines = [line.split()[0] for line in f.readlines() if line != '\n']
            f.close()
        return lines
    
    def write_words(lines, filename='Somali Words.txt'):
        with open(filename, 'w') as f:
            for line in lines:
                f.write(line)
                f.write('\n')
            f.close()
    

    Example usage:

    words = get_words()
    write_words(words)
    

    Or, alternatively:

    if __name__ == '__main__':
        words = get_words()
        write_words(words)