1

I'm attempting to average the lengths of each word after reading from a file. The text inside the file, however, is not formatted with normal sentence structure. Sometimes there is an extra space between words and new line breaks mid sentence.

Current code

def average(filename):
    with open(filename, "r") as f:
        for line in f:
            words = line.split()
            average = sum(len(words) for words in words)/len(words)
            return average

>>>4.3076923076923075

Expected
>>>4.352941176470588

File

Here are some words   there is no punctuation but there are words what
is the average length
4
  • please provide full code. return can only be used inside a function. Commented Oct 10, 2015 at 20:39
  • @marmeladze just edited Commented Oct 10, 2015 at 20:44
  • you say you attempting to calculate the average length of each string, do you mean words or number of words per line? Also, you might want to edit the double meaning of the name words in the code Commented Oct 10, 2015 at 20:47
  • average length of each word inside the file Commented Oct 10, 2015 at 20:48

1 Answer 1

2

When you open the file as f, then run

for x in f:

x will be each line in the file, ended by a newline. The answer you are getting is perfectly correct for the first line of text. If you want the second line to be included in the first one, you'll need to process the text file as a whole, and not line by line.

Assuming you want to get the average of all the words in the file, the following should work a little better:

def average(filename):
    with open(filename, "r") as f:
        lines = [line for line in f]
        words = " ".join(lines).split()
        average = sum(len(word) for word in words)/len(words)
    return average
Sign up to request clarification or add additional context in comments.

4 Comments

would you care to provide an example? I'm fairly new to Python coming from Java
@23k are there multiple entries in the file, or is this it? If this is the only entry, just " ".join() each line
this is the only entry.
Awesome! Thanks for the help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.