Skip to content

Instantly share code, notes, and snippets.

@tombrad
Last active March 14, 2024 15:50
Show Gist options
  • Select an option

  • Save tombrad/4697060 to your computer and use it in GitHub Desktop.

Select an option

Save tombrad/4697060 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() function. 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 …
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list() # list for the desired output
for line in fh: # to read every line of file romeo.txt
word= line.rstrip().split() # to eliminate the unwanted blanks and turn the line into a list of words
for element in word: # check every element in word
if element in lst: # if element is repeated
continue # do nothing
else : # else if element is not in the list
lst.append(element) # append
lst.sort() # sort the list (de-indent indicates that you sort when the loop ends)
print lst # print the list
@JusticeSelormBruce

Copy link
Copy Markdown

Capture

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
word_split = line.split()
for word in word_split:
if word not in lst:
lst.append(word)
else:
continue

print(sorted(lst))

@shubham1686

Copy link
Copy Markdown

This one is some tricky with two nested loops. If someone has a simpler code is welcome! :)

This is the simpler method and workable too:

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

@faespana

Copy link
Copy Markdown

Hello my friend, I found a different solution :)

Check it...hehehe

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
a = []
for line in fh:

line = line.rstrip()   
wds = line.split()
a = a + wds
a.sort()

del a[6:8]
del a[12:14]
del a[19:20]
del a[20:22]

print(a)

@carloslambrano00

Copy link
Copy Markdown

Thank you!
btw now in python3 is input not raw_input

@justacuriousperson

justacuriousperson commented May 20, 2021

Copy link
Copy Markdown

fname = input("Enter file name: ")

try:
fh = open(fname)
except:
print("invalid file name")
quit()
lst=list()
for line in fh:
line=line.rstrip()
line=line.split()
for words in line:
if words in lst:
continue
else:
lst.append(words)
lst.sort()
print(lst)

hi guys, this is my code and it works but was just wondering why do some code on top not need line=line.rstrip()?
is it because print() does not print the \n out?

@NaomiPham200296

Copy link
Copy Markdown
fname = input("Enter file name: ")
fh = open(fname,'r')
lst = []
for line in fh:
    text1 = line.split()
    for word in text1:
        if word in lst: continue
        else:
            lst.append(word.strip())
lst.sort()
print(lst)

what is the lst = [ ] if I may ask. I dont understand that line much

@will-1997

Copy link
Copy Markdown

name = "mbox-short.txt"
handle = open(name)
counts = {}
words = []

for line in handle:
line = line.rstrip()
if not line.startswith('From '):
continue
word = line.split()
words.append(word[1])

for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print(sorted(counts,key=counts.get, reverse = True)[0]+' '+str(sorted(counts.values(), reverse=True)[0]))

@MarvinSheng

Copy link
Copy Markdown

Thank you!

@mener2021

mener2021 commented Sep 17, 2021

Copy link
Copy Markdown

Hi, this is a code i used to display in the format asked by the exercise

romeo example code2

@ammy8588

Copy link
Copy Markdown

with open('admin panel.txt','a') as s:
pplzz tell correct line

@sandy928

sandy928 commented Oct 4, 2021

Copy link
Copy Markdown

8 4

@snehaguptaa

Copy link
Copy Markdown

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

@ShashwatHarsh1

Copy link
Copy Markdown

I have a question, I am really new to codding
instead of opening file I just have used the text as variable, everything is working but it is not sorting itself, please help

fname = '''But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief'''
fname = fname.split()
lst = list(fname)
fname = fname.sort()
print(lst)

ghost commented Nov 8, 2021

Copy link
Copy Markdown

fname = input("Enter file name: ")
try:
fh = open(fname)
except:
print("file does not exist")
lst = list()
for line in fh:
line=line.rstrip()
line=line=line.split()
for word in line:
if word in lst:
continue
else:
lst.append(word)
lst.sort()
print(lst)

@Karim-Monir

Copy link
Copy Markdown

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

@davidados

Copy link
Copy Markdown
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    line = line.split(" ")
    for word in line:
        word = word.strip()
        if word not in lst:
            lst.append(word)

lst.sort()
print(lst)

@VinayReddy-Vangala

Copy link
Copy Markdown

fname = input("Enter file name: ") # Input file name
fh = open(fname) # File opens and stored in fh
lst = list() # Intiating list named lst(note list name cant be list so opted for lst)
for line in fh: # 1st iteration a 1st line in fh
stripped_line=line.rstrip() # Strips the extra spaces and new line spaces
split_list= stripped_line.split() # Split() method stores values of each line with a commma separated value in list, we named that list as split_list
for each_word in split_list: # We are looping to find the words in split_list
if each_word not in lst: # If the word is not present in our empty list it gets added to the list if not it gets ignored
lst.append(each_word) # Finally we add those which are not present in lst
print(sorted(lst)) # We can use lst.sort() or sorted(lst)

@deleonab

Copy link
Copy Markdown

filename = input("Enter file:")
if len(filename) < 1:
filename = "mbox-short.txt"
handle = open(filename,'r')
mydict = dict()

for line in handle:
if not line.startswith('From') or line.startswith('From:'):
continue
else:
line.rstrip()
words = line.split()
timestring = words[5].split(':')
hourstring = timestring[0]

    mydict[hourstring]= mydict.get(hourstring,0) + 1

for (v,k) in sorted(mydict.items()):
print(v,k)

@deleonab

Copy link
Copy Markdown

I have a question, I am really new to codding instead of opening file I just have used the text as variable, everything is working but it is not sorting itself, please help

fname = '''But soft what light through yonder window breaks It is the east and Juliet is the sun Arise fair sun and kill the envious moon Who is already sick and pale with grief''' fname = fname.split() lst = list(fname) fname = fname.sort() print(lst)

This will sort it. But remember that upper case will sort before lowercase.

fname = '''But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief'''
fname = fname.split()
lst = list(fname)
print(sorted(lst))

@Adelynweige

Adelynweige commented May 27, 2022

Copy link
Copy Markdown

### i also had problem with 'double' and is there anybody can help further?thx
actally i have understood that we use a blank space after'from'
or we write a conditional sentence like if not len(line) <=3 then continue
the goal is to ensure that we avoid those blank lines
but i still have the question that why cannot use rstrip() here to help avoid those blank lines
for i had tried it but if we do not use a blank space after'from' or write a conditional sentence
the result still doubles
why is that on earth?

@MaryamFarshbafi

Copy link
Copy Markdown

fname = input("Enter file name: ")

fh = open(fname)
wod=[]
lst = list()
for line in fh:
nm=line.split()
for charcter in nm:
if charcter not in wod:
wod.append(charcter)
wod.sort()

print(wod)

@Dwongg

Dwongg commented Sep 7, 2022

Copy link
Copy Markdown

:)

file = input("Enter a file name:")
handle = open(file)
read = handle.read()

lst = list( )
for line in read:
line = read.split( )
for w in line:
if w not in lst:
lst.append(w)

lst.sort()
print(lst)

@P-SPN

P-SPN commented Oct 6, 2022

Copy link
Copy Markdown

fname = input("Enter the file name:")
fhandle = open(fname)
words = list()
for line in fhandle:
line = line.split()

[words.append(i) for i in line if i not in words] // without the need of 'for' loop

for i in line:
    if i not in words:
        words.append(i)

words.sort()
print(words)

@longcheng2022

Copy link
Copy Markdown

fname = input("Enter file name: ")
fname='romeo.txt'
fh = open(fname)
lst = list()
for line in fh:
word_split=line.split()
for w in word_split:
if w not in lst:
lst.append(w)
else:
continue
lst.sort()
print(lst)

@ibrahim0moakkit

Copy link
Copy Markdown

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
temp=list()
count=0
for line in fh:
if line.startswith("From "):
words=line.split()

   lst.append(words[1:2])

for element in lst:
for x in element:
print(x)
count+=1

print("There were", count, "lines in the file with From as the first word")

@ali6406

ali6406 commented Mar 16, 2023

Copy link
Copy Markdown

image

Not the best but works well. :)

@ShuckZ77

Copy link
Copy Markdown

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
lst2 = []
for line in fh:
q=line.rstrip()
w=q.split()

for word in w:
    if word not in lst:
        lst.append(word)
    
    else:
        continue

#print(q)

#print(lst2)
lst.sort()
print(lst)
#print()

@Apodaca98

Apodaca98 commented Aug 19, 2023

Copy link
Copy Markdown

I don't know why when I run the code I get none, help me.

fname = "8.4.txt"
fh = open(fname)
fh = fh.read().split()
lst = []
indice = len(fh)
for i in range(indice):
if fh[i] not in lst:
lst.append(fh[i])
lst = lst.sort()
print(lst)

@theoriginalkamdia

Copy link
Copy Markdown

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

@Inspire2023

Copy link
Copy Markdown

fname = input("Enter file name: ")

try :
fh = open(fname)
except:
print("File Does not Exist!")

lst = list()

for line in fh:
words = line.split()
for word in words:
if word in lst: continue

    lst.append(word)
lst.sort()

print(lst)

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