Skip to content

Instantly share code, notes, and snippets.

@zcakzwa
Created July 5, 2016 03:20
Show Gist options
  • Save zcakzwa/c04fb15f6fffc1d3fdb2f761608b6582 to your computer and use it in GitHub Desktop.
Save zcakzwa/c04fb15f6fffc1d3fdb2f761608b6582 to your computer and use it in GitHub Desktop.
8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in…
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line=line.rstrip()
line= line.split()
for c in line:
if c in lst:
continue
else:
lst.append(c)
lst.sort()
print lst
@joguiguma
Copy link

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
line = line.split()
for c in line:
if c in lst:
continue
else:
lst.append(c)
lst.sort()
print(lst)

@MRodHer
Copy link

MRodHer commented Sep 19, 2020

You do not need to strip. And this way is easier:

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.split()
for words in line:
if words not in lst:
lst.append(words)
lst.sort()
print(lst)

@luqkrzy
Copy link

luqkrzy commented Sep 30, 2020

# if in continue used
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    add_word = line.rstrip().split()
    for i in add_word:
        if i in lst: continue
        else: lst.append(i)
lst.sort()
print(lst)

# inf not in used
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    add_word = line.split()
    for i in add_word:
        if i not in lst: lst.append(i)
lst.sort()
print(lst)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment