photo
This code can't load the log.txt file.
The file is in the temp folder.
Why can't I load it?
This code only displays the text: Search word: ABC.
text = input("Search word: ABC")
with open("C:\Temp\log.txt", encoding = "utf-8") as f:
cnt = 0
for line in f:
l = line.strip().split()
if (l[-1] == text):
print(line.strip())
cnt += 1
if (cnt): print(cnt, "count")
else: print(text, "No data.")
It seems like you need to type the word after running the program. The "ABC" you see is the prompt from the script i.e. it is not entered by you. That's why the program keeps running, waiting for the input and doesn't go further.
Here's your code slightly modified to make it clear.
text = input("Search word: ")
with open("C:\Temp\log.txt", encoding="utf-8") as f:
cnt = 0
for line in f:
if text in line:
print(line.strip())
cnt += 1
if cnt:
print(cnt, "count")
else:
print(text, "No data.")
I guess you understand that your code:
ask the user to input some text
count the occurrences of that text in the file C:\Temp\log.txt, under the conditions:
the text does not contains space
the text is at the end of the line
the text may be followed by one or more spaces
the text must be preceded by one or more spaces
the file cannot have empty lines
Under those conditions, your code should behave nicely. I would recommend to change text = input("Search word: ABC") to text = input("Search word: ") to make it clear that the user need to input some text.
If you still have unexpected results, check if you don't have any character encoding issue (like a terminal default encoding not being utf-8)
Related
i want to replace a set of characters from a text file when i give a work with blanks in it like for example :
i gave the line The Language Is _th_n !
it should return python replacing _ with text from a file like text.txt
i wrote this code please check once
with open('data/text','r', encoding='utf8') as file:
word_list = file.read()
def solve(message):
hint = []
for i in range(15,len(message) - 1):
if message[i] != '\\':
hint.append(message[i])
hint_string = ''
for i in hint:
hint_string += i
hint_replaced = hint_string.replace('_', '!')
solution = re.findall('^'+hint_replaced+'$', word_list, re.MULTILINE)
return solution```
I am trying to create a block of code that scans a .txt file (first book of LOTR) and tallys the frequency of each letter into a dictionary. (say for instance if theres 500 3 letter words appearing in the book, the output will be displayed as 3:500, and so on).
I seemed to have gotten the code right as I have tried it on test documents before adding the dict() function, and it works by printing each word as a string in a list, though when I go to run it now, it prints the first word then outputs file not found (which is what ive coded for an exception), even though the file is present in my jupyter notebook.
Is there any way to fix this? what is the default directory that jupyter scans for?
All of your help is appreciated!
Code:
fname= input('Enter file: ')
#if len(fname) < 1: fname = 'LOTR.txt'
try:
fhand = open(fname)
d = dict()
for line in fhand:
words = line.split()
print(words)
for word in words:
d1[word] = d1.get(word, 0) + 1
print (d1)
except:
print("File not found")
output:
Enter file: LOTR.txt
['PROLOGUE']
File not found
Your problem is that you are accessing d1 before defining it.
Also you should catch specific exceptions instead of using a bare except. The following should solve your problem:
fname= input('Enter file: ')
#if len(fname) < 1: fname = 'LOTR.txt'
try:
fhand = open(fname)
d = dict()
for line in fhand:
words = line.split()
print(words)
for word in words:
d[word] = d.get(word, 0) + 1
print(d)
except FileNotFoundError:
print("File not found")
except Exception as e:
print("Other error occurred", e)
So I'm currently trying to write some code that opens and reads a text file. The text file contains a short paragraph. Within the paragraph, there are some words with brackets around them, which could look like: "the boy [past_tense_verb] into the wall." I am trying to write code that looks for the brackets in the text file, and then displays to the user the words in the text file, for the user to then write some input that will replace the bracketed words. This is the code I have so far:
f = open('madlib.txt', 'r')
for line in f:
start = line.find('[')+1
end = line.find(']')+1
word = line[start:end+1]
inputword = input('Enter a ' + word + ': ')
print(line[:start] + inputword + line[end:])
Any help is greatly appreciated - thanks!
import re
with open('madlib.txt', 'r') as f:
data = f.read()
words_to_replace = re.findall(r"\[(\w+)\]", data)
replace_with = []
for idx, i in enumerate(words_to_replace):
print(f"Type here replace \033[1;31m{i}\033[1;m with:", end =" ")
a = input()
replace_with.append(a)
for idx, i in enumerate(replace_with):
data = data.replace(words_to_replace[idx], i)
with open('newmadlib.txt', 'w') as f:
f.write(data)
I wrote an applescript to generate a text file of all unwatched movies in my itunes library. Here is the code of that script:
tell application "iTunes"
set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
if (count unwatchedEpisodes) > 0 then
set trackNames to {}
repeat with anEpisode in unwatchedEpisodes
set tmp to location of anEpisode as text
set posixtmp to POSIX path of tmp
set end of trackNames to (posixtmp as text)
end repeat
set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
set unwatchedTVShows to trackNames as text
do shell script "echo " & quoted form of unwatchedTVShows & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"
#display dialog trackNames as text
set AppleScript's text item delimiters to TID
end if
set watchedEpisodes to tracks of playlist "Movies" whose unplayed is false and played count > 0
set unwatchedEpisodes to tracks of playlist "Movies" whose unplayed is true
if (count unwatchedEpisodes) > 0 then
set trackNames to {}
repeat with anEpisode in unwatchedEpisodes
set tmp to location of anEpisode as text
set posixtmp to POSIX path of tmp
set end of trackNames to (posixtmp as text)
end repeat
set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
set unwatchedMovies to trackNames as text
do shell script "echo " & quoted form of unwatchedMovies & " > /Volumes/Data/Media/Kodi/unwatchedMovies.txt"
#display dialog trackNames as text
set AppleScript's text item delimiters to TID
end if
end tell
Here is my output file:
/Volumes/Data/Media/Movies/Thanks For Sharing.m4v
/Volumes/Data/Media/Movies/Thats My Boy.m4v
/Volumes/Data/Media/Movies/Think Like a Man.m4v
/Volumes/Data/Media/Movies/Think Like a Man Too.m4v
/Volumes/Data/Media/Movies/This Means War.m4v
/Volumes/Data/Media/Movies/Top Five.m4v
/Volumes/Data/Media/Movies/Trail of Blood.m4v
My problem is reading this file. I need to open it, and put it in a string so that I can search it wholeistically (ie, if I search for "Think Like a Man" I don't want a false positive on "Think Like a Man Too".
Anyway, here is my current python code (or at least a snippet of that code):
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
for line in umovies:
line = line.strip()
print line
Here is the output:
/Volumes/Data/Media/Movies/Trail of Blood.m4voo.m4v
Clearly, it's opening and reading the file, but I'm not understanding why the snippet isn't providing a full "list" of what's in the text file. Any thoughts as to what I'm doing wrong?
Here is the final answer. Not sure exactly what's different than what I had before (mixing tabs and spaces maybe??). Anyway, for future reference, this code:
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as uwmovies:
for line in uwmovies:
line = line.replace("\n","")
unwatchedmovies = line.split('\r')
print unwatchedmovies
Gave the output of this list:
['/Volumes/Data/Media/Movies/Table 19.m4v', '/Volumes/Data/Media/Movies/Term Life.m4v', '/Volumes/Data/Media/Movies/Thanks For Sharing.m4v', '/Volumes/Data/Media/Movies/Thats My Boy.m4v', '/Volumes/Data/Media/Movies/Think Like a Man.m4v', '/Volumes/Data/Media/Movies/Think Like a Man Too.m4v', '/Volumes/Data/Media/Movies/This Means War.m4v', '/Volumes/Data/Media/Movies/Top Five.m4v', '/Volumes/Data/Media/Movies/Trail of Blood.m4v']
which was exactly what I needed. I list with no "\r" or "\n"'s. Thanks for the help!
Is this your actual code snippet?
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
for line in umovies:
line = line.strip()
print line
This would only print the last line of your file. Note, print line is only indented one tab.
Try calling .read() on the file you open and then split the content up on \n (newline)
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
for line in umovies.read().split('\n'):
line = line.strip()
print line
But this is probably enough for your usecase:
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
umovies_content = umovies.read()
print umovies_content
Try This ( Pythonic Way, UPDATED ) :
import sys
read_lines = [sys.stdout.write(line.rstrip('\n') + "\n") for line in open('1.txt')]
Python 2x
from __future__ import print_function
read_lines = [print(line.rstrip('\n')) for line in open('1.txt')]
I am able to open the rules file and create a dictionary to use for my encryption. I have to also create a dictionary to use for decrypting text. I assume it's basically the same function with minor changes. The encrypt works fine, but I can't get the decrypt to work. My second problem is that while I encrypted the file I took out all spaces and punctuation. I can't figure out how to get those back in the output file once I run the program. It just prints in a single column. Lastly I have to output this to a .txt file. I am able to create a .txt with a user assigned name, but can't get anything to print on the file.
Here is what I achieved so far.
#import clauses
import string
#function definitions
#encrypt dictionary
def createrulesdictencrypt(openFile):
rulesencrypt1 = {}
for line in openFile:
rulessplit = string.split(string.strip(line))
rulesencrypt1[rulessplit[0]] = rulessplit[1]
return rulesencrypt1
#decrypt dictionary
def createrulesdictdecrypt(openFile):
rulesdecrypt1 = {}
for line in openFile:
rulessplit = string.split(string.strip(line))
rulesdecrypt1[rulessplit[1]] = rulessplit[0]
return rulesdecrypt1
openFile = open('rules.txt', 'r')
rulesencrypt = createrulesdictencrypt(openFile)
rulesdecrypt = createrulesdictdecrypt(openFile)
#print rulesencrypt
#print rulesdecrypt
#function for encrypting file
def encryptfile(openFile2):
for line in openFile2:
for word in line.split():
empty = ''
for char in word:
if char not in string.punctuation:
char=char.lower()
empty = empty+char
if len(empty) == 2:
print rulesencrypt[empty]
empty = ''
if len(empty) == 1:
print rulesencrypt[empty]
#function for decrypting file
def decryptfile(openFile2):
for line in openFile2:
for word in line.split():
empty = ''
for char in word:
if char not in string.punctuation:
char=char.lower()
empty = empty+char
if len(empty) == 2:
print rulesdecrypt[empty]
empty = ''
if len(empty) == 1:
print rulesdecrypt[empty]
#main program
ende = raw_input("To encrypt a file, enter '0':\nTo decrypt a file, enter '1':")
filename = raw_input("Enter the name of the file to be processed:")
outfilename = raw_input("Enter the name of the file to save the result to:")
openFile2 = open(filename, 'r')
outputfile = open(outfilename, 'w')
fileencrypt = encryptfile(openFile2)
filedecrypt = decryptfile(openFile2)
if ende == "0":
print encryptfile(fileencrypt)
if ende == "1":
print decryptfile(filedecrypt)
This is what I am trying to encrypt
Sir Robin: "Oh, you liars!"
Minstrel: [singing] "Bravely taking to his feet, he beat a very brave
retreat. A brave retreat by brave Sir Robin."
Your first problem is that you're not actually writing your encrypted text to a file, instead you're just printing it to sys.stdout. Incidentally, print appends a \n to it's output by default.
You could rewrite your decrypt function as follows:
#function for decrypting file
def decryptfile(openFile2, outfile): # <- CHANGED to add outfile
for line in openFile2:
for word in line.split():
empty = ''
for char in word:
if char not in string.punctuation:
char=char.lower()
empty = empty+char
if len(empty) == 2:
outfile.write(rulesdecrypt[empty]) # <- CHANGED to write to file
empty = ''
if len(empty) == 1:
outfile.write(rulesdecrypt[empty]) # <- CHANGED to write to file
You will then need to invoke the decryptfile function with a file as its second argument. A similar change could be made to the encryptfile function.
With respect to punctuation and whitespace, either encrypt it or just leave it in place. Once you've removed it, there really isn't a good way to replace it.