i have 3 files in my folder. (pythonapp.py, numbers.txt, usednumbers.txt).
So basically my app grabs a random string from (numbers.txt) and saves it to a variable. Then it writes the variable to (usednumbers.txt). But the problem is i don't want to get any duplicate strings written to (usednumbers.txt). So i'd like my app to check whenever it grabs a new random string from (numbers.txt), that if it has been already used in the past (so if it exists in usednumbers.txt)
#imports-------------------------------
import random
#variables-----------------------------
line = random.choice(open('numbers.txt').readlines()) #get a random string
textfile = open("usednumbers.txt", "a") #open usednumbers txt file
#main----------------------------------
#here: need to check if our selected random variable "line"
#is in txt file "usednumbers.txt", if it exists there, we get a new random number
#if it doesn't exist there, we continue and write the variable there (below)
textfile.write(line) #store the number we are going to use
textfile.close() #so in future we avoid using this number again
You can modify your code little checking again and again into the file will be overkill and reading is time expensive.
So you can read number file and filter the number which are not present in usednumber and choose a random number from it.
#imports-------------------------------
import random
#variables-----------------------------
numbers = open('numbers.txt').read().splitlines() #get a random string
# alreday in usednumbes
already_in_file = set([x for x in open("usednumbers.txt", "r").read().splitlines()])
# filtering only those number swhich are not in number.txt
numbers = [x for x in numbers if x not in already_in_file]
#choose random number
if len(numbers) >0 :
line = random.choice(numbers)
#main----------------------------------
textfile = open("usednumbers.txt", "a") #open usednumbers txt file
textfile.writelines(str(line)+"\n") #store the number we are going to use
textfile.close() #so in future we avoid using this number again
You can check if the chosen line is in the lines of the text file.
#imports-------------------------------
import random
#variables-----------------------------
line = random.choice(open('numbers.txt').readlines()) #get a random string
textfile = open("usednumbers.txt", "a") #open usednumbers txt file
#main----------------------------------
#here: need to check if our selected random variable "line"
#is in txt file "usednumbers.txt", if it exists there, we get a new random number
#if it doesn't exist there, we continue and write the variable there (below)
while(line in open('usednumbers.txt').readlines()):
line = random.choice(open('numbers.txt').readlines()) #get a random string
textfile.write(line) #store the number we are going to use
textfile.close() #so in future we avoid using this number again
Update:
Not the most time performant solution.
See the solution provided by #Suryaveer Singh for a more optimized solution.
This question already has answers here:
How to count word "test" in file on Python?
(5 answers)
Closed 2 years ago.
I am trying to make this program read a specific word in a text file, but the outcome only comes as "1". Why is this happening?
import os
openfile = input('Enter the input file: ')
accumulator = 0
entry = "PMID"
if os.path.isfile(openfile):
file = open(openfile,'r')
for entry in file.readlines():
accumulator +=1
print('there are:',accumulator)
exit()
print('Input file not found.')
print('Please check the file name or the location of your input file.')
Thank you so much!
If you are looking to count how many times a certain word comes up we can use python's built-in str.count() function in order to do so. See documentation here:
https://docs.python.org/3/library/stdtypes.html?highlight=str%20count#str.count
Here is how it could be used in your case:
openfile = input('Enter the input file: ') # Gets the input file from the user
word = 'PMID' # The word we are trying to count
try:
with open(openfile, 'r') as f:
# Uses a context manager (the 'with' keyword) so that we do not need to manually close the file
word_count = f.read().count(word)
# Reads the entire file and then uses the built-in count() function to determine how many times the entry appears
print(f'The word {word} appears {word_count} times.')
quit() # Exits the program
except FileNotFoundError:
print('Input file not found.')
print('Please check the file name or the location of your input file.')
I hope this was what you were looking for!
You may try something like:
for line in file:
accumulator += entry in line
# This does not work if the entry occurs more than once on the same line.
The problem is that you are calling exit() inside your for loop. This means that after the first iteration (when accumulator=1), you are ending the loop. Move this instruction out of the loop for this to work properly.
import os
openfile = input('Enter the input file: ')
accumulator = 0
word = "PMID"
if os.path.isfile(openfile):
file = open(openfile,'r')
for entry in file.readlines():
accumulator +=1
print(f'There are {accumulator} occurences of "{word}" in {openfile}')
else:
print('Input file not found.')
print('Please check the file name or the location of your input
If you then want to count the occurences of a specific word...
import os
openfile = input('Enter the input file: ')
accumulator = 0
word = "PMID"
if os.path.isfile(openfile):
file = open(openfile,'r')
for entry in file.readlines():
if word in entry:
accumulator +=1
print(f'There are {accumulator} occurences of "{word}" in {openfile}')
else:
print('Input file not found.')
print('Please check the file name or the location of your input file.')
I am currently working on a beginner problem
(https://www.reddit.com/r/beginnerprojects/comments/1i6sax/challenge_count_and_fix_green_eggs_and_ham/).
The challenge is to read through a file, replacing lower case 'i' with 'I' and writing a new corrected file.
I am at a point where the program reads the input file, replaces the relevant lower case characters, and writes a new corrected file. However, I need to also count the number of corrections.
I have looked through the .replace() documentation and I cannot see that it is possible to find out the number of replacements made. Is it possible to count corrections using the replace method?
def capitalize_i(file):
file = file.replace('i ', 'I ')
file = file.replace('-i-', '-I-')
return file
with open("green_eggs.txt", "r") as f_open:
file_1 = f_open.read()
file_2 = open("result.txt", "w")
file_2.write(capitalize_i(file_1))
You can just use the count function:
i_count = file.count('i ')
file = file.replace('i ', 'I ')
i_count += file.count('-i-')
file = file.replace('-i-', '-I-')
i_count will have the total amount of replacements made. You can also separate them by creating new variables if you want.
My code pretty much asks user input and a pre made text which it prints to the .txt file. I want to add the character calculator to print into the file, not as a print. Is it possible?
input = input(str("Type something: "))
file = open("harjoitus.txt", "w")
file.write(str("This code is here automatically.\n"))
file.write(str(input))
file.write(str("\n",))
file.close()
with open("harjoitus.txt", 'r') as file:
text = file.read().strip().split()
len_chars = sum(len(word) for word in text)
print(len_chars)
This pretty much prints the amount of characters as print not to the text file how I want it. Is it possible to edit this somehow that it prints the character amount straight to the file and not as a print?
First before you go into this appending, take a look at how many places you are calling str() its unnecessary most of these values are already stings and ready to be written. Also avoid variable names like input that have preassigned purposes in python. But to add this count to the end, collections.Counter is an option, you should open the file as a append. Then you can add this number to the end of your file.
from collections import Counter
user = input("Type something: ")
with open('harjoitus.txt', 'w') as f:
f.write("This code is here automatically.\n")
f.write(user)
f.write("\n")
with open('harjoitus.txt', 'r') as f:
content = f.read()
c = Counter(content)
tot = sum(c.values())
with open('harjoitus.txt', 'a') as f:
f.write(str(tot))
chrx#chrx:~/python/stackoverflow/10.11$ python3.7 stack.py
Type something: vash
chrx#chrx:~/python/stackoverflow/10.11$ cat harjoitus.txt
This code is here automatically.
vash
38
-
Hi friends.
I have a lot of files, which contains text information, but I want to search only specific lines, and then in these lines search for on specific position values and multiply them with fixed value (or entered with input).
Example text:
1,0,0,0,1,0,0
15.000,15.000,135.000,15.000
7
3,0,0,0,2,0,0
'holep_str',50.000,-15.000,20.000,20.000,0.000
3
3,0,0,100,3,-8,0
58.400,-6.600,'14',4.000,0.000
4
3,0,0,0,3,-8,0
50.000,-15.000,50.000,-15.000
7
3,0,0,0,4,0,0
'holep_str',100.000,-15.000,14.000,14.000,0.000
3
3,0,0,100,5,-8,0
108.400,-6.600,'14',4.000,0.000
And I want to identify and modify only lines with "holep_str" text:
'holep_str',50.000,-15.000,20.000,20.000,0.000
'holep_str',100.000,-15.000,14.000,14.000,0.000
There are in each line that begins with the string "holep_str" two numbers, at position 3rd and 4th value:
20.000 20.000
14.000 14.000
And these can be identified like:
1./ number after 3rd comma on line beginning with "holep_str"
2./ number after 4th comma on line beginning with "holep_str"
RegEx cannot help, Python probably sure, but I'm in time press - and go no further with the language...
Is there somebody that can explain how to write this relative simple code, that finds all lines with "search string" (= "holep_str") - and multiply the values after 3rd & 4th comma by FIXVALUE (or value input - for example "2") ?
The code should walk through all files with defined extension (choosen by input - for example txt) where the code is executed - search all values on needed lines and multiply them and write back...
So it looks like - if FIXVALUE = 2:
'holep_str',50.000,-15.000,40.000,40.000,0.000
'holep_str',100.000,-15.000,28.000,28.000,0.000
And whole text looks like then:
1,0,0,0,1,0,0
15.000,15.000,135.000,15.000
7
3,0,0,0,2,0,0
'holep_str',50.000,-15.000,40.000,40.000,0.000
3
3,0,0,100,3,-8,0
58.400,-6.600,'14',4.000,0.000
4
3,0,0,0,3,-8,0
50.000,-15.000,50.000,-15.000
7
3,0,0,0,4,0,0
'holep_str',100.000,-15.000,28.000,28.000,0.000
3
3,0,0,100,5,-8,0
108.400,-6.600,'14',4.000,0.000
Thank You.
with open(file_path) as f:
lines = f.readlines()
for line in lines:
if line.startswith(r"'holep_str'"):
split_line = line.split(',')
num1 = float(split_line[3])
num2 = float(split_line[4])
print num1, num2
# do stuff with num1 and num2
Once you .split() the lines with the argument ,, you get a list. Then, you can find the values you want by index, which are 3 and 4 in your case. I also convert them to float at the end.
Also final solution - whole program (version: python-3.6.0-amd64):
# import external functions / extensions ...
import os
import glob
# functions definition section
def fnc_walk_through_files(path, file_extension):
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
if filename.endswith(file_extension):
yield os.path.join(path, filename)
# some variables for counting
line_count = 0
# Feed data to program by entering them on keyboard
print ("Enter work path (e.g. d:\\test) :")
workPath = input( "> " )
print ("File extension to perform Search-Replace on [spf] :")
fileExt = input( "> " )
print ("Enter multiplier value :")
multiply_value = input( "> " )
print ("Text to search for :")
textToSearch = input( "> " )
# create temporary variable with path and mask for deleting all ".old" files
delPath = workPath + "\*.old"
# delete old ".old" files to allow creating backups
for files_to_delete in glob.glob(delPath, recursive=False):
os.remove(files_to_delete)
# do some needed operations...
print("\r") #enter new line
multiply_value = float(multiply_value) # convert multiplier to float
textToSearch_mod = "\'" + textToSearch # append apostrophe to begin of searched text
textToSearch_mod = str(textToSearch_mod) # convert variable to string for later use
# print information line of what will be searched for
print ("This is what will be searched for, to identify right line: ", textToSearch_mod)
print("\r") #enter new line
# walk through all files with specified extension <-- CALLED FUNCTION !!!
for fname in fnc_walk_through_files(workPath, fileExt):
print("\r") # enter new line
# print filename of processed file
print(" Filename processed:", fname )
# and proccess every file and print out numbers
# needed to multiplying located at 3rd and 4th position
with open(fname, 'r') as f: # opens fname file for reading
temp_file = open('tempfile','w') # open (create) tempfile for writing
lines = f.readlines() # read lines from f:
line_count = 0 # reset counter
# loop througt all lines
for line in lines:
# line counter increment
line_count = line_count + 1
# if line starts with defined string - she will be processed
if line.startswith(textToSearch_mod):
# line will be divided into parts delimited by ","
split_line = line.split(',')
# transfer 3rd part to variable 1 and make it float number
old_num1 = float(split_line[3])
# transfer 4th part to variable 2 and make it float number
old_num2 = float(split_line[4])
# multiply both variables
new_num1 = old_num1 * multiply_value
new_num2 = old_num2 * multiply_value
# change old values to new multiplied values as strings
split_line[3] = str(new_num1)
split_line[4] = str(new_num2)
# join the line back with the same delimiter "," as used for dividing
line = ','.join(split_line)
# print information line on which has been the searched string occured
print ("Changed from old:", old_num1, old_num2, "to new:", new_num1, new_num2, "at line:", line_count)
# write changed line with multiplied numbers to temporary file
temp_file.write(line)
else:
# write all other unchanged lines to temporary file
temp_file.write(line)
# create new name for backup file with adding ".old" to the end of filename
new_name = fname + '.old'
# rename original file to new backup name
os.rename(fname,new_name)
# close temporary file to enable future operation (in this case rename)
temp_file.close()
# rename temporary file to original filename
os.rename('tempfile',fname)
Also after 2 days after asking with a help of good people and hard study of the language :-D (indentation was my nightmare) and using some snippets of code on this site I have created something that works... :-) I hope it helps other people with similar question...
At beginning the idea was clear - but no knowledge of the language...
Now - all can be done - only what man can imagine is the border :-)
I miss GOTO in Python :'( ... I love spaghetti, not the spaghetti code, but sometimes it would be good to have some label<--goto jumps... (but this is not the case...)