Python script to delete specific word in text file line - python-2.7

i have a text file with some site links.... i want to remove the string which is before the site name.
here is the input file >>
input.txt:
http://www.site1.com/
http://site2.com/
https://www.site3333.co.uk/
site44.com/
http://www.site5.com/
site66.com/
output file should be like:
site1.com/
site2.com/
site3333.co.uk/
site44.com/
site5.com/
site66.com/
here is my code:
bad_words = ['https://', 'http://', 'www.']
with open('input.txt') as oldfile, open('output.txt', 'w') as newfile:
for line in oldfile:
if not any(bad_word in line for bad_word in bad_words):
newfile.write(line)
print './ done'
when i run this code then it totally remove the lines which containing bad_words
site44.com/
site66.com/
what should i do with code to get my specific result?

Thanks all i have solved this... code should be:
fin = open("input.txt")
fout = open("output.txt", "w+")
delete_list = ['https://', 'http://', 'www.']
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
print './ done'

Related

rstrip, split and sort a list from input text file

I am new with python. I am trying to rstrip space, split and append the list into words and than sort by alphabetical order. I don’t what I am doing wrong.
fname = input("Enter file name: ")
fh = open(fname)
lst = list(fh)
for line in lst:
line = line.rstrip()
y = line.split()
i = lst.append()
k = y.sort()
print y
I have been able to fix my code and the expected result output.
This is what I was hoping to code:
name = input('Enter file: ')
handle = open(name, 'r')
wordlist = list()
for line in handle:
words = line.split()
for word in words:
if word in wordlist: continue
wordlist.append(word)
wordlist.sort()
print(wordlist)
If you are using python 2.7, I believe you need to use raw_input() in Python 3.X is correct to use input(). Also, you are not using correctly append(), Append is a method used for lists.
fname = raw_input("Enter filename: ") # Stores the filename given by the user input
fh = open(fname,"r") # Here we are adding 'r' as the file is opened as read mode
lines = fh.readlines() # This will create a list of the lines from the file
# Sort the lines alphabetically
lines.sort()
# Rstrip each line of the lines liss
y = [l.rstrip() for l in lines]
# Print out the result
print y

File "<string>", line SyntaxError: unexpected EOF while parsing

I am trying to do this exercise but fail. I can only get this result:
main() File "C:\Users\chemuser\Desktop\KHL\python\chapter4_6.py", line 22, in main
asciimark = eval(line) File "<string>", line 1
^ SyntaxError: unexpected EOF while parsing
here is my fail code:
# -*- coding: cp1252 -*-
#A certain CS professor gives 5-point quizzes that are
#graded on the scale 5-A, 4-B, 3-C, 2-D, 1-F, 0-F.
#Write a program that accepts a quiz score as an
#input and prints out the corresponding grade.
import string
def main():
#set up file names
infileName = raw_input("input file name: ")
outfileName = raw_input("output file name: ")
#open files
infile = open(infileName, "r")
outfile = open(outfileName, "w")
#process each line of the input file
for line in infile.readlines():
#get the mark from line
asciimark = eval(line)
#creat grade
allgrade = "FEDCBA"
grade = allgrade[asciimark]
#write it to the output file
outfile.write(grade+"\n")
#close both files
infile.close()
outfile.close()
print "Done!"
main()
the input file is look like this (just a column of number 0 - 5, no blank line between):
5
1
0
2
3
I did a test, I add '/n' in the first line (5/n), it shows:
main() File "C:\Users\chemuser\Desktop\KHL\python\chapter4_6.py", line 22, in main
asciimark = eval(line) File "<string>", line 1
5\n
^ SyntaxError: unexpected character after line continuation character
your comments are very appreciated!!

Python : count function does not work

I am stuck on an exercise from a Coursera Python course, this is the question:
"Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line:
From stephen.marquard#uct.ac.za Sat Jan 5 09:14:16 2008
You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end.
Hint: make sure not to include the lines that start with 'From:'.
You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt"
Here is my code:
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for line in fh:
words = line.split()
if len(words) > 2 and words[0] == 'From':
print words[1]
count = count + 1
else:
continue
print "There were", count, "lines in the file with From as the first word"`
The output should be a list of emails and the sum of them, but it doesn't work and I don't know why: actually the output is "There were 0 lines in the file with From as the first word"
I used your code and downloaded the file from the link. And I am getting this output:
There were 27 lines in the file with From as the first word
Have you checked if you are downloading the file in the same location as the code file.
fname = input("Enter file name: ")
counter = 0
fh = open(fname)
for line in fh :
line = line.rstrip()
if not line.startswith('From '): continue
words = line.split()
print (words[1])
counter +=1
print ("There were", counter, "lines in the file with From as the first word")
fname = input("Enter file name: ")
fh = open(fname)
count = 0
for line in fh :
if line.startswith('From '): # consider the lines which start from the word "From "
y=line.split() # we split the line into words and store it in a list
print(y[1]) # print the word present at index 1
count=count+1 # increment the count variable
print("There were", count, "lines in the file with From as the first word")
I have written all the comments if anyone faces any difficulty, in case you need help feel free to contact me. This is the easiest code available on internet. Hope you benefit from my answer
fname = input('Enter the file name:')
fh = open(fname)
count = 0
for line in fh:
if line.startswith('From'):
linesplit =line.split()
print(linesplit[1])
count = count +1
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for i in fh:
i=i.rstrip()
if not i.startswith('From '): continue
word=i.split()
count=count+1
print(word[1])
print("There were", count, "lines in the file with From as the first word")
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for line in fh:
if line.startswith('From'):
line=line.rstrip()
lt=line.split()
if len(lt)==2:
print(lt[1])
count=count+1
print("There were", count, "lines in the file with From as the first word")
My code looks like this and works as a charm:
fname = input("Enter file name: ")
if len(fname) < 1:
fname = "mbox-short.txt"
fh = open(fname)
count = 0 #initialize the counter to 0 for the start
for line in fh: #iterate the document line by line
words = line.split() #split the lines in words
if not len(words) < 2 and words[0] == "From": #check for lines starting with "From" and if the line is longer than 2 positions
print(words[1]) #print the words on position 1 from the list
count += 1 # count
else:
continue
print("There were", count, "lines in the file with From as the first word")
It is a nice exercise from the course of Dr. Chuck
There is also another way. You can store the found words in a separate empty list and then print out the lenght of the list. It will deliver the same result.
My tested code as follows:
fname = input("Enter file name: ")
if len(fname) < 1:
fname = "mbox-short.txt"
fh = open(fname)
newl = list()
for line in fh:
words = line.split()
if not len(words) < 2 and words[0] == 'From':
newl.append(words[1])
else:
continue
print(*newl, sep = "\n")
print("There were", len(newl), "lines in the file with From as the first word")
I did pass the exercise with it as well. Enjoy and keep the good work. Python is so much fun to me even though i always hated programming.

PYTHON - Read and overwrite file and add each value by one

I’m trying to program a simple code in python that will overwrite my existing file and also add one to every value or line in my file.
For example my “num.txt” file:
5 ---> 6
7 ---> 8
9 ---> 10
11 ---> 12
13 ---> 14
file = raw_input("Enter filename: ")
infile = open(file,'r')
for line in infile:
value = int(line)
infile.write(str(value + 1))
infile.truncate()
infile.close()
Error message:
infile.write(str(value + 1))
IOError: File not open for writing
I really appreciate your help
Thx
Geno
Your file is not open for writing, this line
infile = open(file,'r')
means that open the file for reading.
If you want to open the file for writing, you can use 'w' (write) or 'r+' (read and write) use this instead:
infile = open(file,'r+')
for more you can read (http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python) --> Mode Section.
If you use 'r+' the code should be something like
infile = open(file, 'r+')
for line in infile:
val = int(line)
infile.write(str(val + 1) + '\n')
infile.truncate()
infile.close()
But I suppose this wont serve the purpose which you want to do, this will just append the values to the end. If you want to write these new values to file, use this instead:
infile = open(file, 'r')
lines = infile.readlines() #this gives a list of all lines
infile.close()
outfile = open(file, 'w') #erases previous contents
for line in lines:
outfile.write(str(int(line) + 1) + '\n') #if you are sure file have int's only
outfile.close()
For Python 3,
filename = input("Enter filename: ")
with open(filename, 'r+') as file:
lines = file.readlines()
file.seek(0)
for line in lines:
value = int(line)
file.write(str(value + 1))
file.truncate()

List to Text or Replace word in Text File

So I have a text file that contains:
Toy_One Ordered
Toy_Two Ordered
Toy_Three Ordered
I want to remove the " Ordered" from the text file. I figured making a list and rewriting to the file would be simple, or even a replace but clearly not. So far, I have been only able to rewrite Toy_Three.
Infile = (src.txt, "r")
g = list(Infile)
stripg = [mark.strip() for mark in g]
for line in stripg:
entry = line.split(" Ordered")
NewList = list(entry[0])
InOutFile = (src, "w")
for final in NewList:
InOutFile.write(final)
My outcome is just Toy_Three
I've also tried "pickle" but with no success.
Any help would be appreciated, thanks.
Nevermind, got it:
Infile = (src.txt, "r")
magic = Infile.readlines()
delete = [" Ordered"]
Outfile = (src.txt, "w")
for line in magic:
for word in delte:
line = line.replace(word,"")
Outfile.write(line)