Python - Replacing Single Letter for each instance found in a line - python

I have a python line that has
/c/hossam/fawzy/
this sentence
I want to replace all the forward slashes whenever they are found in a line, I am really wanting to use the replace method. so here is what I've done.. and I've reached the point when I print "Yeah Found" whenever I see it in the for loop, but can't figure out how to replace it.
import sys
file = open(r"E:\AutomationTestPath\t2.py", 'r+')
contents = file.read()
ListContents = list(contents)
print(ListContents)
SearchingFor = '/'
for letter in ListContents:
if SearchingFor in letter:
print("Yeah Found")

Try:
import re
sentence = "/c/hossam/fawzy/"
sentence = re.sub(r"/", r"-", sentence) # Replace '/' with '-'
print(sentence)
Output:
-c-hossam-fawzy-

import re
file = open(r"E:\AutomationTestPath\t2.py", 'r+') #Opening The FIle
contents = file.read()
Sentence = str(contents) #Converting to String
sentence = re.sub(r"/", r"-", Sentence)
print(sentence)

Related

how to find the longest_word by using searching loop

Write a function longest_word that asks the user for words and returns the longest word entered by the user. It should stop when the user hits return without typing a word. If multiple words have the same maximum length, return the first word entered by the user. If the user quits before entering any words, return “No words were entered”. This function should use a searching loop.
(Hint: remember that the len function returns the length of a string.)
Takes list of files and a next and checks if the words in file appear in those files.
Code:
def list_search_dictionary(fname, listfname):
for search in listfname:
with open(fname,'r') as f1:
with open(search,'r') as f2:
#splits word by word
All = f2.read().split()
formater = lambda x:x.strip().lower()
#formats each element
All = list(map(formater,All))
for word in f1:
word = formater(word)
if word in All:
print(f'Found: {word}')
Using your functions:
Change your function to:
def my_search_dictionary(search_dic, fname):
# read the file
infile = open(fname,"r")
# look for each line in the file
for line in infile:
# remove the string at the end of the line
line_strip = line.strip()
# lowercase
line_lower = line_strip.lower()
# i love dogs
# more than hotdogs
# split " " in the line and make them in the list
line_split = line_lower.split(" ")
# ["i"," love dogs"]
# ["more", " than", " hotdogs"]
# look for each search term in the line_split
for word in line_split:
# check if every word in the line
for key in search_dic:
if word == key:
search_dic[key] += [fname]
infile.close()
The third function would be:
def list_search_dictionary(fname, listfname):
search_dic = key_emptylist(fname)
for file in listfname:
search_dic = my_search_dictonary(search_dic,file)

Removing characters in a file and also making it neat

I want to basically remove all the characters in delete list from the file (Line 11 to 15). What would be the neatest way to delete the words without making the code not neat. I am not sure whether to open the file again here which I know would not be the right way but I can't think of a different solution. Any help would be appreciated.
from os import write
import re
def readText():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt') as f:
print(f.read())
def longestWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r+') as f:
users_text = f.read()
#I want to basically remove all the char in delete list from the file. What would be the neatest way to delete the words without making the code not neat. I am not sure wether to open the file again here and re write it or what!
deleteList = ['!','£','$','%','^','&','*','()','_','+']
for line in f:
for word in deleteList:
line = line.replace(word, '')
longest = max(users_text.split(), key=len)
count_longest = str(len(longest))
print('The longest word in the file is: ' + long)
print('Thats a total of '+count_longest+' letters!')
def writeWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'w') as f:
users_text = input('Enter your desired text to continue. \n: ')
f.write(users_text)
f.close()
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r') as file:
print(file.read())
longestWord()
Had to re work it and implement it in a different def. Need to add relative paths and will be alot cleaner aswell.
from os import write
import re
def longestWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r+') as f:
users_text = f.read()
longest = max(users_text.split(), key=len)
count_longest = str(len(longest))
print('The longest word in the file is: ' + longest)
print('Thats a total of '+count_longest+' letters!')
def writeWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'w') as f:
users_text = input('Enter your desired text to continue. \n: ')
cleanText = re.sub('[^a-zA-Z0-9 \n\.]', ' ', users_text)
f.write(cleanText)
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r') as clean:
print('\nRemoved any illegal characters. Here is your text:\n\n' + cleanText + '\n')
f.close()
while True:
print("""
Welcome to Skies word text counter!
====================================================
""")
writeWord()
longestWord()
userDecide = input("""
====================================================
Would you like to enter new text and repeat?
Type 'yes' to continue else program will terminate.
====================================================
: """)
if not userDecide.lower == 'yes':
print('Application closing...')
exit()

Add a char to the beginning and end of each line in a file

I have a text file that each line contains exactly one word. I want update the file by attaching a char to the beginning and end of each word in each line. Here is my code in Python:
appendText='_'
names=open("name.txt",'r')
updatedNames=open("name2.txt",'a')
for name in names:
updatedNames.write(appendText+name+appendText)
updatedNames.close()
But the problem is this code add the _ to the end of line after the \n char. In other words, the output looks like this:
_Name
_
_Name followed by an enter and then in the next line there another _. I want to both _ to be in the same line:
_Name_
You can use str.rstrip() to get rid of that \n:
appendText = '_'
with open("name.txt", 'r') as names:
with open("name2.txt", 'a') as updatedNames:
for name in names:
updatedNames.write(appendText + name.rstrip() + appendText + '\n')
And use the context manager to open your text files.
You want to remove the newline and then add it back:
appendText='_'
names=open("name.txt",'r')
updatedNames=open("name2.txt",'a')
for name in names:
updatedNames.write(appendText + name.rstrip() + appendText + '\n')
updatedNames.close()
you can try this:
append_text = "_"
with open("name.txt") as f:
buff = []
for line in f:
if line.strip():
buff.append("%s%s%s"% (append_text,line.strip(),append_text))
updatedNames=open("name2.txt",'w')
updatedNames.write("\n".join(buff))
updatedNames.close()
empty lines will be ignored
I would remove the \n automatically with readlines() after you opened the file:
mylist = names.readlines()
newstring = []
for word in list:
newstring += appendText+word+appendText+'\n'
then print this to your file

Python search for text over multiple lines

import os
searchquery = 'word'
with open('Y:/Documents/result.txt', 'w') as f:
for filename in os.listdir('Y:/Documents/scripts/script files'):
with open('Y:/Documents/scripts/script files/' + filename) as currentFile:
for line in currentFile:
if searchquery in line:
start = line.find(searchquery)
end = line.find("R")
result = line[start:end]
print result
f.write(result + ' ' +filename[:-4] + '\n')
Now this works well to search for "word" and prints everything after word up until an "R" providing that it is on the same line. However if the "R" is on the line it won't print the stuff before it.
eg:
this should not be printed!
this should also not be printed! "word" = 12345
6789 "R" After this R should not be printed either!
In the case above the 6789 on line 3 will not be printed with my current. However i want it to be. How do i make python keep going over multiple lines until it reaches the "R".
Thanks for any help!
It is normal that it does not print the content on the next line because you are searching for the word on one line. A better solution would be as follows.
import os
searchquery = 'word'
with open('Y:/Documents/result.txt', 'w') as f:
for filename in os.listdir('Y:/Documents/scripts/script files'):
with open('Y:/Documents/scripts/script files/' + filename) as currentFile:
content = ''.join([line for line in currentFile])
start = content.find(searchquery)
end = content.find("R")
result = content[start:end].replace("\n", "")
print result
f.write(result + ' ' +filename[:-4] + '\n')
Please be advised, this will work only for a single occurence. You will need to break it up further to print multiple occurences.

Censor Words from a File Using a CensorFile - Python

I'm trying to create a 'censor' program which reads in a 'censorlist' with words to censor out of a 'censorfile'. I feel like I'm close, but when I run the program it's only censoring one line. Any help would be greatly appreciated!
#!/usr/bin/python
import sys, os
censorlist = raw_input("File with words to censor? ")
if os.path.isfile(censorlist):
print "The file", censorlist, "exists!"
else:
print "The file", censorlist, "doesn't exist!"
sys.exit()
print ""
filterword = {}
for currentline in censorlist:
line = currentline.strip()
filterword.append(line)
censorfile = raw_input("File to censor using provided list? ")
script = []
for currentline in censorfile:
line = currentline.strip()
script.append(line)
for lines in script:
results = []
words = lines.split()
for word in words:
if word in filter:
results.append("****")
else:
results.append(word)
resultfile = open(censorfile, 'w')
for items in results:
resultfile.write(items)
You just use the string's replace method to replace each instance of a substring...
'foo bar spam foo'.replace('foo', '****') # '**** bar spam ****'
You just need to iterate over the list of words to censor and call replace for each.
for word in censorlist:
string.replace(word, '****')

Categories

Resources