In the below function after doing some operations to print few words after some processing,i wish to print all the output words in a file,however rather than 4 words which are being produced as output only 2 are being written in the file words.txt.
def morsePartialDecode(inputStringList):
with open('words.txt','w') as wordfile:
message_received = inputStringList
message_received = ' '.join(inputStringList)
for i in range(len(message_received)):
x = 'x'
y = '.'
message = message_received.replace(x, y)
message1 = message.split(",")
message_conv = morseDecode(message1)
print message_conv
print >> wordfile, (message_conv)
for i in range(len(message_received)):
x = 'x'
y = '-'
message = message_received.replace(x, y)
message2 = message.split(",")
message_converted = morseDecode(message2)
print >> wordfile, (message_converted)
wordfile.close()
return message_converted
As an output of the function i am getting the the words:
EESE
TTDT
SAIFE
DMNCT
However in the file only SAIFE and DMNCT are written.Where did it went wrong.Any help would be appreciated.
You don't need to close the file if you're using a with statement if python.
You're opening the file in "w" mode, which means that every time you open it, the whole file will be destroyed. Try opening it in append mode.
edit:
Also, I would take a look at the CSV module. It has some great use cases here.
Related
I have a txt file with this in it:
GWashington 83
JAdams 86
What I need to do is read the file, add 5 to the numbers and save it to a new file.
newFile = open('scores2.txt', 'w')
stdLines = [line.strip() for line in open('class_scores.txt')]
scrSep = [line.split(',') for line in stdLines]
print(stdLines, scrSep)
def convert_numbers(s):
if not s:
return s
try:
f = float(s)
i = int(f)
return i if f == i else f
except ValueError:
return s
g = list(map(convert_numbers, scrSep))
print(s)
print(scrSep)
Thank you in advance for your help.
what should happen with this is it should open the file, seperate the lines and seperate the components so then I can turn the numbers into ints and manipulate them. But strip and split are making it harder for the items to be accessed.
Never mind I fixed it, just had to call from deeper in the list.
So instead of list[x] I had to do list[x][y]
That uhh... slipped my mind.
With this input
x 1
x 2
x 3
y 1
y 2
y 3
I'd like to have this output
x 1;2;3
y 1;2;3
Thank you in advance,
Simone
If by terminal you mean something natively built in you might not be in much luck, however you could run a python file from the terminal which could do want you want and more. If having a standalone file isn't possible then you can always run python in REPL mode for purely terminal usage.
If you have python installed all you would need to do to access REPL would be "py" and you could manually setup a processor. If you can use a file then something like this below should be able to take any input text and output the formatted text to the terminal.
file = open("data.txt","r")
lines = file.readlines()
same_starts = {}
#parse each line in the file and get the starting and trailing data for sorting
for line in lines:
#remove trailing/leading whitesapce and newlines
line_norm = line.strip()#.replace('\n','')
#splits data by the first space in the line
#formatting errors make the line get skipped
try:
data_split = line_norm.split(' ')
start = data_split[0]
end = data_split[1]
except:
continue
#check if dictionary same_starts already has this start
if same_starts.get(start):
same_starts[start].append(end)
else:
#add new list with first element being this ending
same_starts[start] = [end]
#print(same_starts)
#format the final data into the needed output
final_output = ""
for key in same_starts:
text = key + ' '
for element in same_starts[key]:
text += element + ";"
final_output += text + '\n'
print(final_output)
NOTE: final_output is the text in the final formatting
assuming you have python installed then this file would only need to be run with the current directory being the folder where it is stored along with a text file called "data.txt" in the same folder which contains the starting values you want processed. Then you would do "py FILE_NAME.ex" ensuring you replace FILE_NAME.ex with the exact same name as the python file, extension included.
I am developing a program which works with a ; separated csv.
When I try to execute the following code
def accomodate(fil, targets):
l = fil
io = []
ret = []
for e in range(len(l)):
io.append(l[e].split(";"))
for e in io:
ter = []
for theta in range(len(e)):
if targets.count(theta) > 0:
ter.append(e[theta])
ret.append(ter)
return ret
, being 'fil' the read rows of the csv file and 'targets' a list which contains the columns to be chosen. While applying the split to the csv file it raises the folowing error: "'l' name is not defined" while as far as I can see the 'l' variable has already been defined.
Does anyone know why this happens? Thanks beforehand
edit
As many of you have requested, I shall provide with an example.
I shall post an example of csv, not a shard of the original one. It comes already listed
k = ["Cookies;Brioche;Pudding;Pie","Dog;Cat;Bird;Fish","Boat;Car;Plane;Skate"]
accomodate(k, [1,2]) = [[Brioche, Pudding], [Cat, Bird], [Car, Plane]]
You should copy the content of fil list:
l = fil.copy()
I'm trying to code a Python script to find files in a directory that contain two keywords in its file contents. I have posted a question before that referred to a basic issue with a much simpler version of this code, but I wasn't sure if I needed to post this separately since I am now looking at a different issue.
import glob
import os
import sqlite3
import re
conn = sqlite3.connect( "C:\\Users\\Jeff\\Documents\\GitHub\\YGOPro Salvation Server\\YGOPro-Support-System\\http\\ygopro\\databases\\0-en-OCGTCG.cdb" )
curs = conn.cursor()
#Define string constants
trig = "EFFECT_TYPE_TRIGGER"
summon = "SUMMON_SUCCESS"
flip = "EFFECT_TYPE_FLIP"
flip2 = "EVENT_FLIP"
pos = "EVENT_CHANGE_POS"
spelltrap = "EFFECT_TYPE_ACTIVATE"
banish = "EVENT_REMOVE"
grave = "EVENT_TO_GRAVE"
os.chdir( "C:\\Users\\Jeff\\Documents\\GitHub\\YGOPro Salvation Server\\Salvation-Scripts-TCG" )
for files in glob.glob( "*.lua" ) :
f = open( files, 'r', encoding = "iso-8859-1" )
for line in f :
files = re.sub('[c.luatilityold]', '', files)
#Use database to print names corresponding to each file ID for verification purpose
result = curs.execute("SELECT id, name FROM texts WHERE ID=?", (files,))
x = result.fetchone()
#Check for files that have both 'trig' and 'banish' values in contents
if trig and banish in line :
if x is not None :
print ( x )
#Check for files that have both 'trig' and 'grave' values in contents
elif trig and grave in line :
if x is not None :
print ( x )
#Check for files that have both 'trig' and 'summon' values in contents
elif trig and summon in line :
if x is not None :
print ( x )
#Check for files that have 'flip' value in contents
elif flip in line :
if x is not None :
print ( x )
#Check for files that have both 'trig' and 'flip2' values in contents
elif trig and flip2 in line :
if x is not None :
print ( x )
#Check for files that have both 'trig' and 'pos' values in contents
elif trig and pos in line :
if x is not None :
print ( x )
#Ignore other files
else :
pass
The issue that I'm having is that the if-cases aren't working properly. The trig variable gets ignored while the code is running, and it therefore only looks at the second key. I have tried using wording such as if trig in line and banish in line, but the problem is that it will only look for files that have these two keys together on the same line of a file's contents. I need this to be able to find a file that has the two keys anywhere in the file. Is there a better way to search for the two keys in one go like how I was trying to do, or is there a different approach that I need to take?
Since this code relies on databases specific to your machine, I cannot test whether my changes work to create your expected outputs.
I am not really sure what you are trying to do here. If you want to search for the keywords in the whole file, read in the entire file at once instead of line by line.
import glob
import os
import sqlite3
import re
conn = sqlite3.connect( "C:\\Users\\Jeff\\Documents\\GitHub\\YGOPro Salvation Server\\YGOPro-Support-System\\http\\ygopro\\databases\\0-en-OCGTCG.cdb" )
curs = conn.cursor()
#Define string constants
trig = "EFFECT_TYPE_TRIGGER"
summon = "SUMMON_SUCCESS"
flip = "EFFECT_TYPE_FLIP"
flip2 = "EVENT_FLIP"
pos = "EVENT_CHANGE_POS"
spelltrap = "EFFECT_TYPE_ACTIVATE"
banish = "EVENT_REMOVE"
grave = "EVENT_TO_GRAVE"
os.chdir( "C:\\Users\\Jeff\\Documents\\GitHub\\YGOPro Salvation Server\\Salvation-Scripts-TCG" )
for filename in glob.glob( "*.lua" ) :
with open(filename, 'r', encoding = "iso-8859-1") as content_file:
content = content_file.read()
query_file = re.sub('[c.luatilityold]', '', filename)
#Use database to print names corresponding to each file ID for verification purpose
result = curs.execute("SELECT id, name FROM texts WHERE ID=?", (query_file ,))
x = result.fetchone()
#Check for files that have both 'trig' and 'banish' values in contents
if trig in content and banish in content:
if x is not None :
print ( x )
#Check for files that have both 'trig' and 'grave' values in contents
elif trig in content and grave in content:
if x is not None :
print ( x )
...
You definitely want to use the syntax
if x in content and y in content
Otherwise, the conditional will always be evaluated to True because the string is always non-empty and will therefore be always True (as indicated in a comment in your last post).
I assumed in your code that the reuse of the variable files in
files = re.sub('[c.luatilityold]', '', files)
#Use database to print names corresponding to each file ID for verification purpose
result = curs.execute("SELECT id, name FROM texts WHERE ID=?", (files,))
x = result.fetchone()
is incidental. Changing the value stored in files should not affect anything else in this instance, but if you try to get the file path of the current file, you will not be getting what you expected. As such, I would also recommend using a different variable for this operation like I did.
i have got this piece of code to find the positions of the first occuring of that word and replace them into the actual program.
i have tried this
sentence = "ask not what you can do for your country ask what your country can do for you"
listsentence = sentence.split(" ")
d = {}
i = 0
values = []
for i, word in enumerate(sentence.split(" ")):
if not word in d:
d[word] = (i + 1)
values += [d[word]]
print(values)
example = open('example.txt', 'wt')
example.write(str(values))
example.close()
how do i write this output to a seperate text file such as notepad.
Actually your code works- example.txt is created each time you run this program. You can check that in your directory this file exists.
If you want to open it right after closing it in your script add:
import os
os.system("notepad example.txt")