String out of first words in a textfile in python

Viewed 34

I cannot solve the following exercise:

In the given function "a_open()" open the file "mytext" and create a string out of the first words in each line of the file. Each word should be separated by a blank (" ").

I am stuck at this point:

a_open():
f= open ("mytext", "r")
for line in f:
print (line.split(' ')[0])

I am aware I should use the function .join but I do not know how. Any suggestions? Thank you in advance!

1 Answers

Assuming this is Python, you might use an approach like passing the filename to the function.

Create an empty list words outside of the loop to hold all the first words per line.

Per line, split on a space, use strip to remove the leading and trailing whitespaces and newlines and filter out the "empty" entries.

If the list is not empty, add the first item to the list.

After processing all the lines, use join with a space on the words list to return a string of all the words.

def a_open(filename):
    words = []
    for line in open(filename, "r"):
        parts = list(filter(None, line.strip().split(' ')))
        if len(parts):
            words.append(parts[0])
    return ' '.join(words)


print(a_open("mytext"))

If the contents of the file is for example

This abc
  is def
      
a

test k lm

The output will be

This is a test

Another option using a regex could be reading the whole file, and use re.findall to return a list of groups.

The pattern ^\s*(\S+) matches optional whitespace chars \s* at the start of the string ^ and captures 1 or more non whitespace chars in group 1 (\S+) which will be returned.

import re

def a_open(filename):
    return ' '.join(
        re.findall(r"^\s*(\S+)",
        open(filename, "r").read(),
        re.MULTILINE)
    )

print(a_open("mytext"))

Output

This is a test
Related