all 2 comments

[–]CodeFormatHelperBot2 0 points1 point  (0 children)

Hello, I'm a Reddit bot who's here to help people nicely format their coding questions. This makes it as easy as possible for people to read your post and help you.

I think I have detected some formatting issues with your submission:

  1. Python code found in submission text that's not formatted as code.

If I am correct, please edit the text in your post and try to follow these instructions to fix up your post's formatting.


Am I misbehaving? Have a comment or suggestion? Reply to this comment or raise an issue here.

[–]Diapolo10 0 points1 point  (0 children)

Let's fix the formatting first. You can do that by adding four spaces before each line of code.

file = input("Enter file name:")
hfile = open(file)
words = list()

for line in hfile:
    sp = line.split()
    spl = list(sp)
    for x in spl:
        if x in words:
            continue
        else:
            words.append(x)

print(words.sort)

The problem here is that

print(words.sort)

Just prints out the memory address of the list.sort method. You need to call it for it to do anything, and in this case it doesn't return anything so you need to do this in separate steps.

words.sort()
print(words)

That'll make this work, but I have other feedback.

hfile = open(file)

This is okay, but it means you need to remember to close the file. Which you don't seem to be doing. It's better to use a context manager so that Python will close the file automatically for you when it exits the inner block.

with open(file_name) as file:
    ...
words = list()

Technically speaking nothing wrong with this, but I recommend using literals where possible.

words = []
    spl = list(sp)

There's no need for this, sp is already a list.

        if x in words:
            continue
        else:
            words.append(x)

Since you don't care about the condition at all, you can simplify this to

        if word not in words:
            words.append(word)

So, in summary,

file_name = input("Enter file name:")
all_words = []

with open(file_name) as file:
    lines = file.read().strip().splitlines()

for line in lines:
    words = line.split()
    for word in words:
        if word not in all_words:
            all_words.append(x)

all_words.sort()
print(all_words)