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, '****')
Related
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)
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)
Trying to write function that recursively counts the number of times word appears in a text file in Python.
def word_count(filename, word):
with open('C:/Users/Ibrahim/Desktop/file.txt', 'r') as f:
result_list = [x.split(',') for x in f.readlines()]
for i in result_list:
if i == word:
return word_count(filename,word)
is what I currently have.
I Think it may helpful for you:
import sys, re
def word_count(filename, niddle, splitter=","):
regex_pattern = '|'.join(map(re.escape, splitter))
with open(filename, 'r') as f:
words = [ word for line in f.read().splitlines() for word in re.split(regex_pattern, line)]
words = filter(None, words)
print "Total Words :", len(words)
print "Searching %s in list" % niddle
print "Total Occurance : %d" % words.count(niddle)
def main(argv):
splitter = ","
if len(argv)==3:
filename, word, splitter = argv
elif len(argv)==2:
filename, word = argv
splitter = splitter
else:
print "Usage : word_count.py <file> <word> <splitter>"
sys.exit()
word_count(filename, word, splitter)
if __name__ == "__main__":
main(sys.argv[1:])
Counter is your friend here, i.e.:
from collections import Counter
f = open('yourfile.txt', 'r')
counts = Counter(f.read().split())
print counts
To check if a specific word exists:
if "myword" in counts:
print "exists"
To get a specific word count value, use:
print counts.get('myword')
# or simply
print counts['myword']
Note:
A Counter is simply a dict subclass and supports all the dict operators and methods.
I am trying to extract complete sentences from a long text file and adding them as strings to a list in Python 2.7. I want to automate this and not just cut and paste in the list.
Here is what I have:
from sys import argv
script, filename = argv # script = alien.py; filename = roswell.txt
listed = []
text = open(filename, 'rw')
for i in text:
lines = readline(i)
listed.append(lines)
print listed
text.close()
Nothing loads to the list.
You can do it with a while loop:
listed = []
with open(filename,"r") as text:
Line = text.readline()
while Line!='':
listed.append(Line)
Line = text.readline()
print listed
In the previous example, I assumed that each sentence is written on a different line, if that's not the case, use this code instead:
listed = []
with open(filename,"r") as text:
Line = text.readline()
while Line!='':
Line1 = Line.split(".")
for Sentence in Line1:
listed.append(Sentence)
Line = text.readline()
print listed
And on a side note, try using with open(...) as text: instead of text = open(...)
Normally sentences are separated by '. ', not '\n'. Under this condition, use split with period+space(without return-enter):
listed = []
fd = open(filename,"r")
try:
data = fd.read()
sentences = data.split(". ")
for sentence in sentences:
listed.append(sentence)
print listed
finally:
fd.close()
I have written a python program to act as a shopping list or some other list editor. It displays the list as it is, then asks if you want to add something, then asks is you want to see the newest version of the list. Here is the code:
#!/usr/bin/python
import sys
def read():
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
print(myList)
myList = []
f.close()
def add_to(str):
newstr = str + "\n"
f = open("test.txt","a") #opens file with name of "test.txt"
f.write(newstr)
f.close()
read()
yes = "yes"
answerone = raw_input("Would you like to add something to the shopping list?")
if answerone == yes:
answertwo = raw_input("Please enter an item to go on the list:")
add_to(bob)
answerthree = raw_input("Would you like to see your modified list?")
if answerthree == yes:
read()
else:
sys.exit()
else:
sys.exit()
When it displays the list it displays it in columns of increasing length.
Instead of this, which is how it appears in the text file:
Shopping List
Soap
Washing Up Liquid
It displays it like this:
['Shopping List\n']
['Shopping List\n', 'Soap\n']
['Shopping List\n', 'Soap\n', 'Washing Up Liquid\n']
I was wondering whether anyone could help me understand why it does this, and how to fix it.
FYI I am using python 2.6.1
EDIT: Thanks to all who commented and answered. I am now trying to edit the code to make it sort the list into alphabetical order, but it is not working. I have written a piece of test code to try and make it work (this would be in the read() function):
#!usr/bin/python
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
f.close()
print myList
subList = []
for i in range(1, len(myList)):
print myList[i]
subList.append(myList[i])
subList.sort()
print subList
This is the text file:
Test List
ball
apple
cat
digger
elephant
and this is the output:
Enigmatist:PYTHON lbligh$ python test.py
['Test List\n', 'ball\n', 'apple\n', 'cat\n', 'digger\n', 'elephant']
ball
apple
cat
digger
elephant
['apple\n', 'ball\n', 'cat\n', 'digger\n', 'elephant']
Once again, any troubleshooting would be helpful.
Thanks
P.S I am now using python 2.7.9
In read, you are printing the whole list after each line read. You just need to print the current line:
def read():
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
print(line)
myList = [] # also you are setting it to empty here
f.close()
Also, you should be using with statement to ensure the closure of the file; and there is no reason to use myList since you are not returning any changes yet; and you'd want to strip() extra whitespace from the beginning and end of the items, so the minimum would be:
def read():
with open('test.txt') as f:
for line in f:
line = line.strip()
print line # this is python 2 print statement
If you need to return a value:
def read():
my_list = []
with open('test.txt') as f:
for line in f:
line = line.strip()
my_list.append(line)
print line
return my_list