Other questions don't seem to be getting answered or are not getting answered for Python. I'm trying to get it to find the keyword "name", set the position to there, then set a variable to that specific line, and then have it use only that piece of text as a variable. In shorter terms, I'm trying to locate a variable in the .txt file based on "name" or "HP" which will always be there.
I hope that makes sense...
I've tried to use different variables like currentplace instead of namePlace but neither works.
import os
def savetest():
save = open("nametest_text.txt", "r")
print("Do you have a save?")
conf = input(": ")
if conf == "y" or conf == "Y" or conf == "Yes" or conf == "yes":
text = save.read()
namePlace = text.find("name")
currentText = namePlace + 7
save.seek(namePlace)
nameLine = save.readline()
username = nameLine[currentText:len(nameLine)]
print(username)
hpPlace = text.find("HP")
currentText = hpPlace + 5
save.seek(hpPlace)
hpLine = save.readline()
playerHP = hpLine[currentText:len(hpLine)]
print(playerHP)
os.system("pause")
save.close()
savetest()
My text file is simply:
name = Wubzy
HP = 100
I want it to print out whatever is put after the equals sign at name and the same for HP, but not name and HP itself.
So it should just print
Wubzy
100
Press any key to continue . . .
But it instead prints
Wubzy
Press any key to continue . . .
This looks like a good job for a regex. Regexes can match and capture patterns in text, which seems to be exactly what you are trying to do.
For example, the regex ^name\s*=\s*(\w+)$ will match lines that have the exact text "name", followed by 0 or more whitespace characters, an '=', and then another 0 or more whitespace characters then a one or more letters. It will capture the word group at the end.
The regex ^HP\s*=\s*(\d+)$ will match lines that have the exact text "HP", followed by 0 or more whitespace characters, an '=', and then another 0 or more whitespace characters then one or more digits. It will capture the number group at the end.
# This is the regex library
import re
# This might be easier to use if you're getting more information in the future.
reg_dict = {
"name": re.compile(r"^name\s*=\s*(\w+)$"),
"HP": re.compile(r"^HP\s*=\s*(\d+)$")
}
def savetest():
save = open("nametest_text.txt", "r")
print("Do you have a save?")
conf = input(": ")
# instead of checking each one individually, you can check if conf is
# within a much smaller set of valid answers
if conf.lower() in ["y", "yes"]:
text = save.read()
# Find the name
match = reg_dict["name"].search(text)
# .search will return the first match of the text, or if there are
# no occurrences, None
if(match):
# With match groups, group(0) is the entire match, group(1) is
# What was captured in the first set of parenthesis
username = match.group(1)
else:
print("The text file does not contain a username.")
return
print(username)
# Find the HP
match = reg_dict["HP"].search(text)
if(match):
player_hp = match.group(1)
else:
print("The text file does not contain a HP.")
return
print(player_hp)
# Using system calls to pause output is not a great idea for a
# variety of reasons, such as cross OS compatibility
# Instead of os.system("pause") try
input("Press enter to continue...")
save.close()
savetest()
Use a regex to extract based on a pattern:
'(?:name|HP) = (.*)'
This captures anything that follows an equal to sign preceded by either name or HP.
Code:
import re
with open("nametest_text.txt", "r") as f:
for line in f:
m = re.search(r'(?:name|HP) = (.*)', line.strip())
if m:
print(m.group(1))
Simplest way may be to use str.split() and then print everything after the '=' character:
with open("nametest_text.txt", "r") as f:
for line in f:
if line.strip():
print(line.strip().split(' = ')[1])
output:
Wubzy
100
Instead of trying to create and parse a proprietary format (you will most likely hit limitations at some point and will need to change your logic and/or file format), better stick to a well-known and well-defined file format that comes with the required writers and parsers, like yaml, json, cfg, xml, and many more.
This saves a lot of pain; consider the following quick example of a class that holds a state and that can be serialized to a key-value-mapped file format (I'm using yaml here, but you can easily exchange it for json, or others):
#!/usr/bin/python
import os
import yaml
class GameState:
def __init__(self, name, **kwargs):
self.name = name
self.health = 100
self.__dict__.update(kwargs)
#staticmethod
def from_savegame(path):
with open(path, 'r') as savegame:
args = yaml.safe_load(savegame)
return GameState(**args)
def save(self, path, overwrite=False):
if os.path.exists(path) and os.path.isfile(path) and not overwrite:
raise IOError('Savegame exists; refusing to overwrite.')
with open(path, 'w') as savegame:
savegame.write(yaml.dump(self.__dict__))
def __str__(self):
return (
'GameState(\n{}\n)'
.format(
'\n'.join([
' {}: {}'.format(k, v)
for k, v in self.__dict__.iteritems()
]))
)
Using this simple class exemplarily:
SAVEGAMEFILE = 'savegame_01.yml'
new_gs = GameState(name='jbndlr')
print(new_gs)
new_gs.health = 98
print(new_gs)
new_gs.save(SAVEGAMEFILE, overwrite=True)
old_gs = GameState.from_savegame(SAVEGAMEFILE)
print(old_gs)
... yields:
GameState(
health: 100
name: jbndlr
)
GameState(
health: 98
name: jbndlr
)
GameState(
health: 98
name: jbndlr
)
I have been referring to Tim Golden python docs and I used the code under "Single image: use PIL and win32ui" on TimGoldenPrintGuide.
I'm trying to print a long bill with an image on the top. For printing the image I have used the same code as in the guide. I have used the code below instead of hDC.DrawText to add the text. If I have a very long text its not getting printed till the end. I used the win32print.WritePrinter to print the same text file and I got it completely. But now as I need to print an image on top I have to use this method with a device context.
In there I pass my string to this TextOut command. So is there is a character length how can I bypass it? Or what is the best way of doing this?
printer_name = sys.argv[1]
filename = sys.argv[2]
image_path = sys.argv[3]
pointSize = int(sys.argv[4])
bill_format = ""
with open(filename) as f:
for line in f:
bill_format += line
for line in (bill_format).split("\n"):
hDC.TextOut((printer_margins[0] + line_space),Y,line)
Y += int (line_space * 1.25)
I created this script that could be used as a login, and then created an external text file that has the data 1234 in it, this is attempting to compare the data from the file, but outputs that the two values are different, even though they are the same. Thanks In advance to any help you can give me, the code I used is below:
getUsrName = input("Enter username: ")
file = open("documents/pytho/login/cdat.txt", "r")
lines = file.readlines()
recievedUsrName = lines[1]
file.close()
print(getUsrName)
print(recievedUsrName)
if recievedUsrName == getUsrName:
print("hello")
elif getUsrName != recievedUsrName:
print("bye")
else:
Try it like:
if recievedUsrName.strip() == getUsrName:
...
It must be the trailing newline.
I can't figure out how to write the user input to an existing file. The file already contains a series of letters and is called corpus.txt . I want to take the user input and add it to the file , save and close the loop.
This is the code I have :
if user_input == "q":
def write_corpus_to_file(mycorpus,myfile):
fd = open(myfile,"w")
input = raw_input("user input")
fd.write(input)
print "Writing corpus to file: ", myfile
print "Goodbye"
break
Any suggestions?
The user info code is :
def segment_sequence(corpus, letter1, letter2, letter3):
one_to_two = corpus.count(letter1+letter2)/corpus.count(letter1)
two_to_three = corpus.count(letter2+letter3)/corpus.count(letter2)
print "Here is the proposed word boundary given the training corpus:"
if one_to_two < two_to_three:
print "The proposed end of one word: %r " % target[0]
print "The proposed beginning of the new word: %r" % (target[1] + target[2])
else:
print "The proposed end of one word: %r " % (target[0] + target[1])
print "The proposed beginning of the new word: %r" % target[2]
I also tried this :
f = open(myfile, 'w')
mycorpus = ''.join(corpus)
f.write(mycorpus)
f.close()
Because I want the user input to be added to the file and not deleting what is already there, but nothing works.
Please help!
Open the file in append mode by using "a" as the mode.
For example:
f = open("path", "a")
Then write to the file and the text should be appended to the end of the file.
That code example works for me:
#!/usr/bin/env python
def write_corpus_to_file(mycorpus, myfile):
with open(myfile, "a") as dstFile:
dstFile.write(mycorpus)
write_corpus_to_file("test", "./test.tmp")
The "with open as" is a convenient way in python to open a file, do something with it while within the block defined by the "with" and let Python handles the rest once you exit it (like, for example, closing the file).
If you want to write the input from the user, you can replace mycorpus with your input (I am not too sure what you want to do from your code snippets).
Note that no carriage return is added by the write method. You probably want to append a "\n" at the end :-)
I am working on a project where I have to edit offsets manually in CNC programs. I would like to do this in python, however, my experience with it has not involved something like this. Any help is greatly appreciated.
example of code:
N0880M41
N0890G50S3600
M03
N0900G96S0210M03
N0910Z23.274M08
N0920M07
N0930Z23.2063
N0940X1.39
N0950G99
N0960G01X1.29F.009
N0970X1.2558
N0980G02X1.189Z23.1662R.944
N0990G01Z14.7569F.012
N1000G02X1.2558Z14.7168R.944
N1010G01X1.29
N1020G00X1.3608Z14.7522
N1030Z23.1309
N1040X1.2656
N1050G01X1.189Z23.1662F.009
N1060G02X1.088Z23.0955R.944
N1070G01Z14.8276F.012
N1080G02X1.2528Z14.7185R.944
N1090G00X1.3236Z14.7538
N1100Z23.0602
N1110X1.1646
N1120G01X1.088Z23.0955F.009
N1130G02X.987Z23.0075R.944
N1140G01Z14.9157F.012
N1150G02X1.1446Z14.7864R.944
N1160G00X1.2152Z14.8217
N1170Z22.9721
N1180X1.0636
N1190G01X.987Z23.0075F.009
N1200G02X.886Z22.8873R.944
N1210G01Z15.0359F.012
N1220G02X1.0344Z14.8716R.944
N1230G00X1.105Z14.907
N1240Z22.8519
I need to change the Z value with a user input via prompt and I wanted to have it output with the same text as the input just with a new value in Z
for example: user prompted and entered value .226
input = N0910Z23.274M08
I would like output to be
output = N0910Z23.500M08
Here is a quick and dirty program that does what you want:
# GCode utility - adjust Z offset
# This code assumes Python 3
import re
def get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
pass
# Regular expression to recognize a Z parameter
z_re = re.compile("Z(-?\d+(?:\.\d*)?)", re.I)
# Create callback function for re.sub
def make_z_callback(dz, fmt="Z{:0.4f}"):
def z_callback(match):
z_value = match.group(1) # get just the number
z_value = float(z_value) + dz # add offset
return fmt.format(z_value) # convert back to string
return z_callback
def main():
# read GCode file contents
fname = input("Enter GCode file name: ")
with open(fname) as inf:
gcode = inf.read()
# do search-and-replace on Z parameters
z_offset = get_float("Enter Z offset: ")
z_callback = make_z_callback(z_offset)
gcode = z_re.sub(z_callback, gcode)
# write result back to file
with open(fname, "w") as outf:
outf.write(gcode)
if __name__=="__main__":
main()